本文目录导读:

JavaScript(前端/Node.js)
function maskPhoneNumber(phone) {
// 移除可能存在的空格或特殊字符
const cleanPhone = phone.replace(/\s+/g, '');
// 验证是否为11位手机号
if (cleanPhone.length !== 11 || !/^1[3-9]\d{9}$/.test(cleanPhone)) {
return phone; // 格式不对返回原值
}
// 隐藏中间4位
return cleanPhone.slice(0, 3) + '****' + cleanPhone.slice(7);
}
// 使用示例
console.log(maskPhoneNumber('13812345678')); // 输出: 138****5678
Python
def mask_phone_number(phone):
# 移除空格
phone = phone.replace(' ', '')
# 验证手机号格式
if len(phone) != 11 or not phone.isdigit():
return phone
# 隐藏中间4位
return phone[:3] + '****' + phone[7:]
# 使用示例
print(mask_phone_number('13812345678')) # 输出: 138****5678
Java
public class PhoneMaskUtil {
public static String maskPhoneNumber(String phone) {
if (phone == null || phone.length() != 11) {
return phone;
}
// 使用正则表达式替换
return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
}
public static void main(String[] args) {
System.out.println(maskPhoneNumber("13812345678")); // 输出: 138****5678
}
}
正则表达式方案(通用)
// 使用正则表达式一步完成
function maskPhone(phone) {
return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
}
支持不同位数的手机号(更灵活)
function maskPhoneCustom(phone, start = 3, length = 4) {
if (!phone || phone.length < start + length) {
return phone;
}
const mask = '*'.repeat(length);
return phone.slice(0, start) + mask + phone.slice(start + length);
}
// 使用示例
console.log(maskPhoneCustom('13812345678')); // 138****5678
console.log(maskPhoneCustom('8613812345678', 2, 5)); // 86*****45678
微信小程序/uni-app
// 在模板中直接使用过滤器
// filter.js
const maskPhone = (phone) => {
if (!phone) return '';
return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};
export { maskPhone };
// 在页面中使用
// <text>{{ phoneNumber | maskPhone }}</text>
数据库查询时处理(SQL)
-- MySQL示例
SELECT
CONCAT(LEFT(phone, 3), '****', RIGHT(phone, 4)) AS masked_phone
FROM users;
-- PostgreSQL示例
SELECT
overlay(phone placing '****' from 4 for 4) AS masked_phone
FROM users;
完整示例(带验证)
function safeMaskPhone(phone) {
// 1. 清除非数字字符
const digits = phone.replace(/\D/g, '');
// 2. 验证是否为11位数字
if (digits.length !== 11) {
throw new Error('手机号格式错误');
}
// 3. 验证国内手机号格式
if (!/^1[3-9]\d{9}$/.test(digits)) {
throw new Error('非有效的手机号格式');
}
// 4. 执行隐藏
return digits.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
}
// 使用
try {
console.log(safeMaskPhone('138 1234 5678')); // 138****5678
} catch (error) {
console.error(error.message);
}
注意事项
- 输入验证:始终先验证手机号格式
- 国际号码:如果需要支持国际号码,调整匹配规则
- 安全性:不要在前端暴露真实完整的手机号
- 性能:正则表达式方法性能较好
- 兼容性:确保方法在所有目标环境中可用
选择适合你技术栈的实现方式,推荐使用正则表达式方案,代码简洁且易于维护。