基地如何刪除在開始和像刪除所有空間的裝飾字符串結尾的.
,使用JavaScript的Javascript在開頭刪除字符串和以下字符串</p> <pre><code>...here.. ..there... .their.here. </code></pre> <p>結束
的輸出應該
here
there
their.here
基地如何刪除在開始和像刪除所有空間的裝飾字符串結尾的.
,使用JavaScript的Javascript在開頭刪除字符串和以下字符串</p> <pre><code>...here.. ..there... .their.here. </code></pre> <p>結束
的輸出應該
here
there
their.here
以下是此任務的RegEx爲的原因:
裏面/()/
是你寫你想要的字符串中找到字符串的模式:
/(ol)/
這將找到字符串中的子ol
。
var x = "colt".replace(/(ol)/, 'a');
會給你x == "cat"
;
在/()/
的^\.+|\.+$
由符號分離成2份|
[手段或]
^\.+
和\.+$
^\.+
裝置以找到許多.
儘可能在開始。
^
表示開始; \是逃避角色;加入+
字符後面表示匹配含有一個任意字符串或多個字符
\.+$
裝置在結束時發現儘可能多的.
越好。
$
意味着最後。
的m
背後/()/
用於指定,如果字符串有換行或回車符,^和$工作人員將會進行匹配,而不是一個串邊界對一個換行符邊界。
落後於/()/
用於執行全局匹配:因此它找到所有匹配而不是在第一次匹配後停止。
要了解關於RegEx的更多信息,您可以查看this guide。
嘗試使用以下正則表達式
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
使用正則表達式使用JavaScript Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');
使用正則表達式/(^\.+|\.+$)/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") + "#");
驚人的解釋,謝謝:3 –
@NikolayTalanov歡迎您:3 –