利用正则隐藏手机号中间四位

该文章展示了如何使用正则表达式和JavaScript的字符串方法(replace,slice,substring,substr)来隐藏手机号码中间的四位数字,以保护隐私。通过匹配和替换,将手机号码转化为如187****1301的形式。
摘要由CSDN通过智能技术生成
// 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值