基于以下字符串。
...here..
..there...
.their.here.
如何使用JavaScript去除字符串开头和结尾的.
,类似于删除所有空格的trim函数。
输出应该是:
here
there
their.here
...here..
..there...
.their.here.
如何使用JavaScript去除字符串开头和结尾的.
,类似于删除所有空格的trim函数。
输出应该是:
here
there
their.here
/(^\.+|\.+$)/mg
的原因:
/()/
中写的是要在字符串中找到的子字符串的模式:
/(ol)/
这将在字符串中找到子字符串ol
。
var x = "colt".replace(/(ol)/, 'a');
将会得到 x == "cat"
;
/()/
中的 ^\.+|\.+$
被符号 |
[表示或] 分成了两部分
^\.+
和\.+$
^\.+
表示在开头找到尽可能多的 .
。
^
表示在开始;\ 是用于转义字符;在字符后添加+
表示匹配包含一个或多个该字符的任意字符串
\.+$
表示在结尾找到尽可能多的 .
。
$
表示在结尾。
/()/
后面的 m
用于指定如果字符串有换行或回车符号,则^和$操作符现在将匹配换行边界,而不是字符串边界。
/()/
后面的g
用于执行全局匹配:因此它会查找所有匹配项,而不仅仅是第一个匹配项。
如果你想更多地了解正则表达式,可以查看这个指南。
尝试使用以下正则表达式
var text = '...here..\n..there...\n.their.here.';
var replaced = text.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/
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") + "#");
replace()
方法来删除字符串中不需要的部分。
示例:
var str = '<pre>I'm big fan of Stackoverflow</pre>'
str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')
console.log(str)
输出:
在规则记录上检查规则
..--'some-name.'--
的不同字符串,我只想保留some-name
,应该做什么变化?我的情况是字符串可能以-'.
开始或结束多次,我想将它们删除。 - Rohit Ambre