JavaScript删除开头和结尾的字符串

24
基于以下字符串。
...here..
..there...
.their.here.

如何使用JavaScript去除字符串开头和结尾的.,类似于删除所有空格的trim函数。

输出应该是:

here
there
their.here
7个回答

39
这就是为什么这个任务的正则表达式是/(^\.+|\.+$)/mg的原因:
  1. /()/ 中写的是要在字符串中找到的子字符串的模式:

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

    var x = "colt".replace(/(ol)/, 'a'); 将会得到 x == "cat";

  2. /()/ 中的 ^\.+|\.+$ 被符号 | [表示或] 分成了两部分

    ^\.+\.+$

    1. ^\.+ 表示在开头找到尽可能多的 .

      ^ 表示在开始;\ 是用于转义字符;在字符后添加+表示匹配包含一个或多个该字符的任意字符串

    2. \.+$ 表示在结尾找到尽可能多的 .

      $ 表示在结尾。

  3. /()/后面的 m 用于指定如果字符串有换行或回车符号,则^和$操作符现在将匹配换行边界,而不是字符串边界。

  4. /()/后面的g用于执行全局匹配:因此它会查找所有匹配项,而不仅仅是第一个匹配项。

如果你想更多地了解正则表达式,可以查看这个指南


讲解得很清楚。谢谢。 - Tushar Shukla
1
@吖奇说-何魏奇ArchyWillHe,如果有类似 ..--'some-name.'-- 的不同字符串,我只想保留 some-name,应该做什么变化?我的情况是字符串可能以 -'. 开始或结束多次,我想将它们删除。 - Rohit Ambre

12

尝试使用以下正则表达式

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

3

这里是可工作的演示

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

  • ^表示在开头
  • \.+表示一个或多个句号
  • $表示在结尾

所以:

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

3

以下是一种不使用正则表达式的答案,它利用了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/


2
稍微更注重代码效率一些,虽然不太容易读懂,但是这个非正则化的原型扩展:
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


1
使用 JavaScript 的正则表达式 Replace
var res = s.replace(/(^\.+|\.+$)/mg, '');

0
我们可以使用replace()方法来删除字符串中不需要的部分。 示例:
var str = '<pre>I'm big fan of Stackoverflow</pre>'

str.replace(/<pre>/g, '').replace(/<\/pre>/g, '')

console.log(str)

输出:

在规则记录上检查规则


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接