UNPKG

china-id-mask

Version:

A utility to mask Chinese ID card numbers by replacing birth date with asterisks

30 lines (25 loc) 963 B
/** * 中国身份证脱敏处理 * @param {string|number} id - 身份证号码 * @returns {string} 脱敏后的身份证号码 * @throws {Error} 如果输入不是有效的中国身份证格式 */ function maskChinaId(id) { // 转换为字符串并去除两端空格 const idStr = String(id).trim(); // 验证身份证长度(15位或18位) if (![15, 18].includes(idStr.length)) { throw new Error('Invalid Chinese ID card length. Must be 15 or 18 digits.'); } // 验证是否为数字(最后一位可以是X) if (!/^[0-9]{17}[0-9Xx]$/.test(idStr) && !/^[0-9]{15}$/.test(idStr)) { throw new Error('Invalid Chinese ID card format.'); } // 处理15位身份证 if (idStr.length === 15) { return idStr.substring(0, 6) + '******' + idStr.substring(12); } // 处理18位身份证 return idStr.substring(0, 6) + '********' + idStr.substring(14); } module.exports = maskChinaId;