在阅读node实战中,有一段代码讲解进行处理可配置的logger中间件,其中有一部分
function setup(options){
const reg = /:(\w+)/g;
return function logger(req,res,next){
const str = options.replace(reg,function(match,property){
return req[property];
})
console.log(str,'str')
next()
}
}
setup(':method :url')
用到了replace进行字符串的匹配取值,因为之前只使用过replace的常规用法,一般第二个参数都是字符串从而进行替换,第二个参数为函数的并不了解,通过这个文章记录并加强学习。
':method :url'.replace(/:(\w+)/g,function(a,b,c,d){
console.log(a,b,c,d)
})
//:method method 0 :method :url
//:url url 8 :method :url
当replace第二个参数为函数时,函数可以有四个参数,a是字符串中匹配到的值,b是正则括号中匹配提取到的值,c是在字符串中匹配到对应值的起始下标,d则是replace作用的字符串,当我们需要对一个字符串进行复杂操作或者多个对象联动操作时,使用replace第二个参数为函数可以有着不错的效果