You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将手机号除前4位外的其余数字替换为星号(适配不同长度)

数字前4位保留、其余替换为星号的实现方案

需求:保留数字字符串(如手机号)的前4位,剩余所有数字替换为星号,支持12位、15位等任意长度的数字。

方法一:字符串截取+星号重复

逻辑直观,先截取前4位,再根据原字符串长度生成对应数量的星号拼接:

function maskNumber(numStr) {
  // 校验输入:必须是纯数字字符串
  if (typeof numStr !== 'string' || !/^\d+$/.test(numStr)) {
    return numStr;
  }
  // 长度≤4时直接返回原内容,无需替换
  if (numStr.length <= 4) {
    return numStr;
  }
  // 拼接前4位和对应数量的星号
  return numStr.slice(0, 4) + '*'.repeat(numStr.length - 4);
}

// 测试示例
const test1 = '447537126710'; // 12位数字
console.log(maskNumber(test1)); // 输出:4475********
const test2 = '138001380001234'; // 15位数字
console.log(maskNumber(test2)); // 输出:1380***********

方法二:正则表达式替换

用正则捕获前4位,将后续数字部分替换为对应长度的星号:

function maskNumberWithRegex(numStr) {
  if (typeof numStr !== 'string' || !/^\d+$/.test(numStr)) {
    return numStr;
  }
  // 捕获前4位,替换后续所有数字为星号
  return numStr.replace(/^(\d{4})(\d+)$/, (_, prefix, suffix) => {
    return prefix + '*'.repeat(suffix.length);
  });
}

// 测试
console.log(maskNumberWithRegex('447537126710')); // 输出:4475********
console.log(maskNumberWithRegex('123456789')); // 输出:1234*****

两种方法都能适配任意长度的数字字符串,输入不符合纯数字格式时直接返回原内容,避免出错。

内容的提问来源于stack exchange,提问作者plisil2000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:35:18