定义一个正则表达式birthdayRegex
,用来匹配特定格式的生日和性别信息,会匹配包含生日和性别信息的字符串。
const birthdayRegex = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{2}(\d)(\d|X)$/;
(\d{6})
匹配身份证号码的前6位,即地区信息。(\d{4})
匹配身份证号码的接下来4位,即出生年份。(\d{2})
匹配身份证号码的接下来2位,即出生月份。(\d{2})
匹配身份证号码的接下来2位,即出生日期。\d{2}
匹配身份证号码的接下来2位,即顺序号。(\d)
匹配身份证号码的倒数第2位,即性别代码。(\d|X)
匹配身份证号码的最后一位,可能是数字也可能是大写字母 X。
使用 match
方法对输入值 value
,即身份证号码进行正则表达式匹配,并将匹配结果存储在 matchResult
变量中。
const matchResult = value.match(birthdayRegex);
console.log(matchResult)
matchResult 是一个数组,其中第一个元素是完整的匹配结果,后续元素是与正则表达式中的捕获组匹配的子串。
从 matchResult 中提取出生日和性别的各个部分,处理后得到结果。
if(matchResult){
const year = matchResult[2];
const month = matchResult[3];
const day = matchResult[4];
const genderCode = matchResult[5];
const birthday = `${year}-${month}-${day}`;
const gender = genderCode % 2 === 0 ? '女':'男'
}
完整代码如下:
// 获取生日和性别
const birthdayRegex = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{2}(\d)(\d|X)$/;
const matchResult = value.match(birthdayRegex);
console.log(matchResult)
if(matchResult){
const year = matchResult[2];
const month = matchResult[3];
const day = matchResult[4];
const genderCode = matchResult[5];
const birthday = `${year}-${month}-${day}`;
const gender = genderCode % 2 === 0 ? '女':'男'
}