function resetPhone(phone) { var str = String(phone) var len = str.length; var prev,next; if (len >= 7) { prev = str.slice(-len,-7) next = str.slice(-3) str = prev+"****"+next } else if (len < 7 && len >= 6) { prev = str.slice(-len,-4) next = str.slice(-2) str = prev + "**" + next } console.log(str) return str}
上面可以正常使用,正则更加方便,但是如果中间连续重复数字有点小问题(如下面的正则方式)。
function resetPhone(phone) { var str = String(phone) var len = str.length; if (len >= 7) { var reg = str.slice(-7, -3) return str.replace(reg, "****") } else if (len < 7 && len >= 6) { //1234567 var reg = str.slice(-4, -2) return str.replace(reg, "**") }}