【问题标题】:String.replace method in javascript using regexjavascript中使用正则表达式的String.replace方法
【发布时间】:2013-06-19 05:05:04
【问题描述】:

我在MDN documentation 中遇到了这个关于在字符串上使用替换方法的示例。

这是那里引用的例子

var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
print(newstr);//Smith,John

我将正则表达式更改为以下内容并进行了测试。

var re = /(\w?)(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$1, $1");
newstr;//J, ohn Smith
var newstr1=str.replace(re,"$2, $1");
newstr1;//ohn, J Smith.

在此示例中,$1 必须是 J,$2 必须是 ohn Smith。 当我颠倒newstr1 的$n 顺序时,它应该是'ohn Smith, J'。但事实并非如此。

我对 $1 和 $2 的理解(子字符串匹配正确)以及为什么 newstr1 不同?

感谢cmets

【问题讨论】:

    标签: javascript string methods replace


    【解决方案1】:

    其实$1"J"$2"ohn"" Smith"是不匹配的。

    var re = /(\w?)(\w+)/,
        str = "John Smith";
    
    str.replace(re, function (match, $1, $2) {
        console.log('match', match);
        console.log('$1', $1);
        console.log('$2', $2);
        return ''; // leave only unmatched
    });
    /* match John
       $1 J
       $2 ohn
       " Smith"
    */
    

    因此,您的交换将在John 之间切换,从而为您提供newstr1

    为什么会发生这种情况?因为\w 匹配一个单词,但? 使它成为可选,所以就像(.*?)(.) 捕获@987654333 中的一个字母@, (\w?) 也在做同样的事情。第二个捕获,(\w+) 然后只能扩展到单词的末尾,尽管+,因为\w 不匹配空格\s

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多