Skip to main content

正则

group

const width1 = '100%';
const width2 = '20px';
const width3 = 719;

console.log(/(?<width>\d+)(?<unit>px|%)$?/.match(width1));

常用的正则

手机号

let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

身份证

const id = ''
let IDReg18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
let IDReg15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
// 校验身份证:
IDReg18.test( id ) || IDReg15.test( id )

提取出生年月

const extractBirthDate = (idNumber) => {
const regex =
/^(?:[1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$|^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;

const match = idNumber.match(regex);
if (match) {
const year = match[1] || match[5];
const month = match[3] || match[7];
const day = match[4] || match[8];

return `${year}-${month}-${day}`;
} else {
return "无效的身份证号码";
}
};