JS regular ID number desensitization

[1]: Description: ID card desensitization processing: /^(.{6})(?:\d+)(.{4})$/, display the first 6 and last 4, and hide the date of birth

const idCard = "110108199001010101"    // 身份证号

const reg = /^(.{6})(?:\d+)(.{4})$/    // 匹配身份证号前6位和后4位的正则表达式

const maskedIdCard = idCard.replace(reg, '\$1******\$2')   // 身份证号脱敏,将中间8位替换为“*”

console.log(maskedIdCard); // 输出:110108******0101

[2]: Description:

In the above code, an ID number variable idCard is first defined , and then a regular expression reg is defined , which matches the first 6 digits and the last 4 digits of the ID number, and uses brackets to separate the first 6 digits and The last 4 bits are grouped separately.

Next, use the replace method to replace the middle 8 digits of the ID number with 8 asterisks. The replacement method is to use $1 to represent the first matched group (that is, the first 6 digits), and use ***** * represents 8 asterisks, use $2 to represent the second matched group (that is, the last 4 digits).

[3]: /^(.{6})(?:\d+)(.{4})$/ This regular expression can be interpreted as:

  • /^ matches the beginning of the string

  • (.{6}) matches 6 arbitrary characters and captures them as the first capturing group

  • (?:\d+) matches one or more digits without capturing them

  • (.{4}) matches 4 arbitrary characters and captures them as the second capturing group

  • $/ matches the end of the string

Guess you like

Origin blog.csdn.net/m0_73461567/article/details/129192760