(可用于身份证或手机号隐藏部分数字)
/**
* @description 替换字符串内指定位置的值
* @param {Number|String} startPosition - 开始位置
* @param {Number|String} endPosition - 结束位置-该位置文本不做替换操作
* @param {String} originStr - 原始文本
* @param {String} replaceStr - 替换文本
* @return {String}
*/
function replaceStr({
startPosition = 0,
endPosition = 0,
originStr = "",
replaceStr = "",
}) {
if (originStr === "") {
throw new TypeError("请传入有效文本!");
}
if (typeof startPosition !== "number") {
startPosition = Number(startPosition);
}
if (typeof endPosition !== "number") {
endPosition = Number(endPosition);
}
if (typeof originStr !== "string") {
originStr += "";
}
if (typeof replaceStr !== "string") {
replaceStr += "";
}
let finalStr = "";
const repeatStrLength = endPosition - startPosition;
const middleStr = "".padEnd(repeatStrLength, replaceStr);
finalStr = `${originStr.slice(0, startPosition)}${middleStr}${originStr.slice(
endPosition
)}`;
return finalStr;
}
// demo
const str = "helloworld";
const replaceStr = replaceStr({
startPosition: 2,
endPosition: 5,
originStr: str,
replaceStr: "*",
});
console.log(replaceStr); //"he***world"
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。