JS给字符串指定位置打码
利用JS将手机号中间四位变成*号
给邮箱和手机号码打码这种功能一般都是后台来做,不建议用前端做
示例
maskString('13878822602', 2); // => '13*********'
maskString('13878822602', 3, 4); // => '138****2602'
maskString('13878822602', 3, 4, 'x'); // => '138xxxx2602'
/**
* 判断一个变量是否为数值
* @param {any} value 需要判断的值
* @param {boolean} isLoose 是否可包含NaN或无限
* @returns {boolean}
*
* isNum(999); // => true;
* isNum(0.1); // => true;
* isNum(NaN); // => false;
* isNum(NaN, true); // => true;
* isNum(Infinity); // => false;
* isNum(Infinity, true); // => true;
* isNum('abc'); // => false;
* isNum('abc', true); // => false;
*/
function isNum(value, isLoose) {
const isNumType = typeof value === "number";
if (isLoose) return isNumType;
return isNumType && !Number.isNaN(value) && Number.isFinite(value);
}
/**
* 判断一个变量是否为字符串
* @param {*} value
* @returns {boolean}
*/
function isStr(value) {
return typeof value === "string";
}
/**
* 判断一个变量是否为undefined
* @param {*} value
* @returns {boolean}
*/
function isUdf(value) {
return value === undefined;
}
/**
* 给字符串指定位置打码
* @param {string} string 需要打码字符串
* @param {number} start 开始位置
* @param {number} length 打码长度
* @param {string} mask 打码符号,默认: *
* @returns {string}
*
* @example
* maskString('13878822602', 2); // => '13*********'
* maskString('13878822602', 3, 4); // => '138****2602'
* maskString('13878822602', 3, 4, 'x'); // => '138xxxx2602'
*/
function maskString(string, start, length, mask) {
const str = String(string);
if (!isNum(start)) return str;
if (isStr(length)) {
mask = length;
length = undefined;
}
if (!isStr(mask)) mask = "*";
const maskStr = str
.substr(start, length)
.replace(/[^\u4e00-\u9fa5]/gm, mask)
.replace(/[\u4e00-\u9fa5]/gm, mask + mask);
const prefix = str.substr(0, start);
const suffix = isUdf(length) ? "" : str.substr(start + length);
return prefix + maskStr + suffix;
}