字符串的replace方法我们最常用到的就是简单的字符串替换,在实际应用中,通过函数来创建一个新的字符串更为方便,代码也更轻巧。
// match 匹配的子串,对应字符串参数的$& p1,p2...正则中第n个括号匹配到的字符串
// offset匹配到的字符串在原字符串中的偏移量 string被匹配的原字符串
str.replace(reg,function(match,p1,p2,p3,offset,string){
// 函数的返回值作为替换字符串
})
1.电话号码的隐藏
// 16789098909 --- 167*****909
function hidePhone(phone){
return `${phone}`.replace(/[^0-9]/ig,'').
replace(/^(\d{3})(.*)(\d{3})/g,fuction(match,pre,middle,last){
return `${pre}${middle.replace(/\d/g,'*')}${last}`
}
)
}
2.短横线转驼峰命名
function toCamelCase(str){
return str.replace(/-(\w)/g, ($0,$1) => {
return $1.toUpperCase()
})
}
3.浏览器参数转换为参数对象
function transformParams(url = '?a=3&b=7&c=liming'){
const params = {}
url.replace(/((\w*)=([\.a-z0-9A-Z]*)?)?/g,(match,str,key,value) => {
if(key || value){
params[key] = value
}
})
return params
}