的Javascript在开头删除字符串和以下字符串

...here.. ..there... .their.here. 

结束

问题描述:

基地如何删除在开始和像删除所有空间的装饰字符串结尾的.,使用JavaScript的Javascript在开头删除字符串和以下字符串</p> <pre><code>...here.. ..there... .their.here. </code></pre> <p>结束

的输出应该

here 
there 
their.here 

以下是此任务的RegEx为的原因:

  1. 里面/()/是你写你想要的字符串中找到字符串的模式:

    /(ol)/这将找到字符串中的子ol

    var x = "colt".replace(/(ol)/, 'a');会给你x == "cat";

  2. /()/^\.+|\.+$由符号分离成2份| [手段或]

    ^\.+\.+$

    1. ^\.+装置以找到许多.尽可能在开始。

      ^表示开始; \是逃避角色;加入+字符后面表示匹配含有一个任意字符串或多个字符

    2. \.+$装置在结束时发现尽可能多的.越好。

      $意味着最后。

  3. m背后/()/用于指定,如果字符串有换行或回车符,^和$工作人员将会进行匹配,而不是一个串边界对一个换行符边界。

  4. 落后于/()/用于执行全局匹配:因此它找到所有匹配而不是在第一次匹配后停止。

要了解关于RegEx的更多信息,您可以查看this guide

+2

惊人的解释,谢谢:3 –

+0

@NikolayTalanov欢迎您:3 –

尝试使用以下正则表达式

var text = '...here..\n..there...\n.their.here.'; 
var replaced = text.replace(/(^\.+|\.+$)/mg, ''); 

使用正则表达式使用JavaScript Replace

var res = s.replace(/(^\.+|\.+$)/mg, ''); 

Here is working Demo

使用正则表达式/(^\.+|\.+$)/mg

  • ^代表在启动
  • \.+一个或多个句号
  • $代表在结束

这样:

var text = '...here..\n..there...\n.their.here.'; 
alert(text.replace(/(^\.+|\.+$)/mg, '')); 

这里是一个非正则表达式的答案,它利用String.prototype

String.prototype.strim = function(needle){ 
    var first_pos = 0; 
    var last_pos = this.length-1; 
    //find first non needle char position 
    for(var i = 0; i<this.length;i++){ 
     if(this.charAt(i) !== needle){ 
      first_pos = (i == 0? 0:i); 
      break; 
     } 
    } 
    //find last non needle char position 
    for(var i = this.length-1; i>0;i--){ 
     if(this.charAt(i) !== needle){ 
      last_pos = (i == this.length? this.length:i+1); 
      break; 
     } 
    } 
    return this.substring(first_pos,last_pos); 
} 
alert("...here..".strim('.')); 
alert("..there...".strim('.')) 
alert(".their.here.".strim('.')) 
alert("hereagain..".strim('.')) 

,看看它在这里工作:http://jsfiddle.net/cettox/VQPbp/

略多码golfy,如果不读,非正则表达式的原型扩展:

String.prototype.strim = function(needle) { 
    var out = this; 
    while (0 === out.indexOf(needle)) 
     out = out.substr(needle.length); 
    while (out.length === out.lastIndexOf(needle) + needle.length) 
     out = out.slice(0,out.length-needle.length); 
    return out; 
} 

var spam = "this is a string that ends with thisthis"; 
alert("#" + spam.strim("this") + "#"); 

Fiddle-ige