JS 将手机号中间四位变为****号的四种方式
1. 正则表达式let tel = '13600136000'tel.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")console.log(tel) // 136****6000
·
1. 正则表达式
let tel = '13600136000';
let result = tel.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
console.log(result); // 136****6000
2. 字符串 substring 方法
var tel = '13600136000';
var result = tel.replace(tel.substring(3,7), "****"); // 利用replace()方法,将电话号码中符合条件的部分替换成 ****,条件就是 tel.substring(3,7) 截取的中间四位字符串
console.log(result); // 136****6000
3. 利用数组的 splice,split,join 方法
let tel = '13600136000';
let array = tel.split(""); //将字符串拆分成数组
array.splice(3,4,"****"); //从数组的第3个开始截取取4个数字,将其替换成'****'
let result = array.join(""); //将剩余的数组项拼接成字符串得到隐藏的手机号
console.log(result); // 136****6000
4. 利用字符串的substr方法
let tel = '13600136000';
var result = tel.substr(0,3) + "****" + tel.substr(7) // 截取字符串的前三项 + **** + 截取字符串的第七项之后的字符串
console.log(result); // 136****6000
更多推荐
已为社区贡献7条内容
所有评论(0)