针对敏感信息脱敏处理!!!!
/**
* @param no 接收的字符串(手机号/身份证号)
* @param start 脱敏起始位置
* @param end 脱敏结束位置(倒数位置)
* @param replace 脱敏个数
* @param split 脱敏标识
* @returns 脱敏后的字符串
*/
const numberDesensitization = (no = '', start = 3, end = 2, replace = 0, split = '*') => {
if (!no) return no
const toStr = no.toString()
let targetStr = ''
const rules = new RegExp(`(\\d{${start}})\\d*(\\d{${end}})`) // 根据首尾脱敏
const rulesReplace = new RegExp(`(\\d{${start}})\\d{${replace}}(\\d*)`) // 根据开始位置和脱敏个数脱敏
for (let i = 0; i < toStr.length; i++) {
if (
(replace && i > Number(start) && i <= Number(start) + Number(replace)) ||
(!replace && i > Number(start) && i <= toStr.length - Number(end))
)
targetStr += split
}
return toStr.replace(replace ? rulesReplace : rules, `$1${targetStr}$2`)
}
需求1:手机号 13921323345 脱敏为: 139******45
numberDesensitization('13921323345')
需求2: 手机号 13921323345 脱敏为:139****3345
// 方法一:
numberDesensitization('13921323345', 3, 4) // 从第3位开始(不包括第3位)脱敏,脱敏到倒数第4位
// 方法二:
numberDesensitization('13921323345', 3, 0, 4) // 从第3位开始(不包括第3位)脱敏,脱敏4位后停止
需求3: 身份证号 150403192206302614 脱敏为:150*************14
numberDesensitization('150403192206302614')
需求4: 身份证号 150403192206302614 脱敏为:15040319********14
numberDesensitization('150403192206302614', 8) // 从第8位开始(不包括第8位)脱敏,脱敏到倒数第2位(默认脱敏到倒数第2位)
需求5: 身份证号 150403192206302614 脱敏为:15040319密密密密密密密密14
// 方法一:
numberDesensitization('150403192206302614', 8, 2, 0, '密')
// 方法二:
numberDesensitization('150403192206302614', 8, 0, 8, '密')
综上:根据传入脱敏的起始位置,结束位置,或传入脱敏个数进行脱敏处理
后期会继续完善~