[英]Javascript Remove strings in beginning and end
基于以下字符串
...here..
..there...
.their.here.
我怎么能删除.
在字符串的开头和结尾,如删除所有空格的修剪,使用javascript
输出应该是
here
there
their.here
这就是为什么这个任务的RegEx是/(^\\.+|\\.+$)/mg
:
在/()/
里面你要编写要在字符串中找到的子字符串的模式:
/(ol)/
这将在字符串中找到子串ol
。
var x = "colt".replace(/(ol)/, 'a');
会给你x == "cat"
;
^\\.+|\\.+$
in /()/
由符号|
分成2部分 [手段或]
^\\.+
和\\.+$
^\\.+
意味着找到尽可能多的人.
尽可能在一开始。
^
表示开头; \\是逃避这个角色; 在字符后面添加+
意味着匹配包含一个或多个字符的任何字符串
\\.+$
意味着找到尽可能多的人.
尽可能在最后。
$
意味着最后。
/()/
后面的m
用于指定如果字符串具有换行符或回车符,则^和$运算符现在将匹配换行符边界而不是字符串边界。
/()/
后面的g
用于执行全局匹配:因此它找到所有匹配而不是在第一次匹配后停止。
要了解有关RegEx的更多信息,您可以查看本指南 。
尝试使用以下正则表达式
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
使用Regex /(^\\.+|\\.+$)/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/
使用RegEx和javaScript 替换
var res = s.replace(/(^\.+|\.+$)/mg, '');
如果不可读的话,非regexp原型扩展稍微更多代码 - 高尔夫:
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") + "#");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.