js的replace方法?

 var str = "xx2016xx2017";
    str = str.replace(/(\d+)/g,function(){
        console.log(arguments[1])
        console.log(RegExp.$1)
    })
    
 
 为什么结果是2016 2017 2017 2017 不应该是2016 2016 2017 2017么
阅读 2.2k
2 个回答

就 ES6 来说(ES5 逻辑也应该类似)

RegExp.prototype[@@replace] 覆盖了默认的 replace 算法

http://www.ecma-international...

11. Repeat, while done is false
    a. Let result be ? RegExpExec(rx, S).
    b. If result is null, set done to true.
    c. Else result is not null,
        i. Append result to the end of results.
        ii. If global is false, set done to true.
        iii. Else,
                ......

可以看到,这里是把正则完全匹配一遍再来替换的

所以不要用全局的结果,替换函数提供了参数可以用

str = str.replace(/(\d+)/g,function(match, p1){
  console.log(arguments[1])
  console.log(p1)
})

https://developer.mozilla.org...

你如果这样写,就得到你要的结果了

var str = "xx2016xx2017";
    str = str.replace(/(\d+)/g,function(re,$1){
        console.log(arguments[1])
        console.log($1)
    })
    
    2016 2016 2017 2017

你的这样的结果的原因是:
当执行 replace对应的正则表达式时,因为是全局的会执行匹配两次 ,而RegExp.$1 代表的是:返回上一次正则表达式匹配中的第一个分组。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题