关于vue.js:JS根据传入参数替换字符内指定位置的值

50次阅读

共计 952 个字符,预计需要花费 3 分钟才能阅读完成。

(可用于身份证或手机号暗藏局部数字)

/**
 * @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"

正文完
 0