js中replace中的回调函数

同时我们使用replace进行字符替换,第二个参数传入替换的参数:

"yyyy-MM-dd".replace(/y+/g,"年")
// 年-MM-dd


但,其实replace的第二个参数可以传入一个回调函数

str.replace(ext, function(){})


参数分别为:

  1. 匹配到的字符串
  2. 如果正则使用了分组匹配就为多个,否则无此参数
  3. 匹配字符串的对应索引位置
  4. 原始字符串

回调函数返回替换的值,如果没有返回,默认为undefined

var str = "yyyy-MM-dd".replace(/(y)+/g, function(a,b,c,d){
    console.log(a,b,c,d)
})
// yyyy y 0 yyyy-MM-dd
// str的值为:undefined-MM-dd
"/* 这是一条注释 */".replace(/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, function(){
    console.log(arguments);
})

结果为:
这里写图片描述
中间的两个undefined是因为([^:]|^)(.*)没有匹配到内容

猜你喜欢

转载自blog.csdn.net/csm0912/article/details/81301961