需求背景
使用正则将地理位置脱敏。
5个字以内,保留第一个字和最后两个字,其余用*
替代;
6到9个字则保留最后五个字,其余用*
替代;
10个字以上则最后五个字的前面四个字代替为*
解决方法
enAdderssFun (text) {
if (text.length && text.length <= 5) {
// 保留第1个字和最后2个字,中间用*替代
return `${text.charAt(0)}${'*'.repeat(text.length - 3)}${text.slice(-2)}`
}
if (text.length > 5 && text.length < 10) {
// 保留最后5个字
return text.replace(/.(?=.{5})/g, '*')
}
if (text.length >= 10) {
// 隐去最后5个字前面的4个字
let reversedStr = [...text].reverse().join('')
let modifiedStr = reversedStr.replace(/(.{5})(.{4})/, (match, g1, g2) => {
return g1 + g2.replace(/./g, '*')
})
let finalStr = [...modifiedStr ].reverse().join('')
return finalStr
}
},
代码解释:
小于5个字时:
`${text.charAt(0)}${'*'.repeat(text.length - 3)}${text.slice(-2)}`
${text.charAt(0)}
:取出文本的第一个字符。
${'*'.repeat(text.length - 3)}
:生成一个由多个星号组成的字符串,长度为原始文本长度减去3。这里使用了repeat()方法,将星号重复多次,以达到生成指定长度的字符串的目的。
${text.slice(-2)}
:取出文本的倒数两个字符。
6-9个字时:
text.replace(/.(?=.{5})/g, '*')
/
:正则表达式的开始。
.
:匹配除换行符以外的任意字符。
(?=.{5})
:零宽正向先行断言。表示匹配位置后面的内容必须是5个字符。
.{5}
:匹配任意5个字符。
/g
:全局匹配。
'*'
:替换匹配到的内容为星号。
大于10个字时:
let reversedStr = [...text].reverse().join('') // 反转
let modifiedStr = reversedStr.replace(/(.{5})(.{4})/, (match, g1, g2) => { // 打码
return g1 + g2.replace(/./g, '*')
})
let finalStr = [...modifiedStr ].reverse().join('') // 反转
将字符串反转,再打码,再反转。因为倒着打码的正则写不出来,所以用了这个方法
结果展示