javascript - js的replace方法?

查看:67
本文介绍了javascript - 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么

解决方案

就 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...

这篇关于javascript - js的replace方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆