名字
function formatName(name) { var newStr; if (name.length === 2) { newStr = name.substr(0, 1) + '*'; } else if (name.length > 2) { var char = ''; for (var i = 0, len = name.length - 2; i < len; i++) { char += '*'; } newStr = name.substr(0, 1) + char + name.substr(-1, 1); } else { newStr = name; } return newStr; } console.log(formatName('张某')); // 张* console.log(formatName('张某人')); // 张*人 console.log(formatName('张某某某人')); // 张***人
手机号
//通过字符串截取中间四位数字,转化为**** function formatPhone(val) { let returnVal = val if (val) { returnVal = val.substr(0, 3) + "****" + val.substr(7) } return returnVal } console.log(formatPhone("15666666666"); // 156****6666)
自定义
function customStar(str,beginLen,endLen) { var len = str.length; var firstStr = str.substr(0,beginLen); var lastStr = str.substr(endLen); var middleStr = str.substring(beginLen, len-Math.abs(endLen)).replace(/[\s\S]/ig, '*'); tempStr = firstStr + middleStr + lastStr; return tempStr; } console.log(customStar('18353246789097654',4,-4)) // "1835*********765"