/**
 * 通用文字脱敏函数
 * @param value 原始文本
 * @param type 脱敏类型 (phone | idCard | name | email | custom)
 * @param options 自定义规则 { keepStart, keepEnd, mask }
 */
export function desensitize(
  value: string,
  type: "phone" | "idCard" | "name" | "email" | "custom" = "custom",
  options?: { keepStart?: number; keepEnd?: number; mask?: string }
): string {
  if (!value) return "";

  const maskChar = options?.mask ?? "*";

  switch (type) {
    case "phone": // 手机号 138****5678
      return value.replace(/^(\d{3})\d{4}(\d{4})$/, `$1${maskChar.repeat(4)}$2`);

    case "idCard": // 身份证 440***********1234
      return value.replace(/^(\d{4})\d{10}(\w{4})$/, `$1${maskChar.repeat(10)}$2`);

    case "name": // 姓名 张三 -> 张* ; 王小明 -> 王*明
      if (value.length <= 2) {
        return value[0] + maskChar;
      } else {
        return value[0] + maskChar.repeat(value.length - 2) + value[value.length - 1];
      }

    case "email": // 邮箱 abc****@qq.com
      return value.replace(/^(.{2}).*(@.*)$/, `$1${maskChar.repeat(4)}$2`);

    case "custom": // 自定义规则
      const keepStart = options?.keepStart ?? 1;
      const keepEnd = options?.keepEnd ?? 1;
      if (value.length <= keepStart + keepEnd) return maskChar.repeat(value.length);
      return (
        value.slice(0, keepStart) +
        maskChar.repeat(value.length - keepStart - keepEnd) +
        value.slice(value.length - keepEnd)
      );

    default:
      return value;
  }
}

使用

参数1:原始文本
参数2: 脱敏类型
参数3  自定义规则
desensitize(“18888888888”,‘phone’) 输出 138*****8888
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐