// 1.利用正则隐藏手机号中间四位
const phone = '18712341301'
// 利用正则划分手机号
const reg = /^(\d{3})\d{4}(\d{4})$/
// str.replace(正则或需要替换的内容,替换为)替换,
// str.repeat(重复次数) 得到重复指定次数后的字符串
// $1 取到正则中第一个()中的内容
// $2 取到正则中第二个()中的内容
const newPhone = phone.replace(reg, `$1${'*'.repeat(4)}$2`)
console.log(newPhone) // 187****1301
// 2.利用字符串截取方法实现
const newPhone2 = phone.replace(phone.slice(3, 7), '****') // str.slice(startIndex,endIndex+1)
const newPhone3 = phone.replace(phone.substring(3, 7), '****') // str.substring(startIndex,endIndex+1)
const newPhone4 = phone.replace(phone.substr(3, 4), '****') // str.substr(startIndex,length)
console.log(newPhone2)
console.log(newPhone3)
console.log(newPhone4)
利用正则隐藏手机号中间四位
最新推荐文章于 2023-12-21 00:13:18 发布
该文章展示了如何使用正则表达式和JavaScript的字符串方法(replace,slice,substring,substr)来隐藏手机号码中间的四位数字,以保护隐私。通过匹配和替换,将手机号码转化为如187****1301的形式。
摘要由CSDN通过智能技术生成