const getInfoByIdcard = function (IdCardNO){
let info = {
age: '', //年龄
gender: '', //性别 M--男 F--女
genderCn: '',//性别 M--男 F--女
status:'201',//解析状态码 200--成功 ,其他--失败
message: '', //解析提示信息
}
// 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
if (reg.test(IdCardNO) === false)
{
info.status = "201"
info.message = "身份证号输入不合法:"+IdCardNO
}
let date = new Date();
let yearfull = date.getFullYear();
if (IdCardNO.length == 18)//18位身份证号处理
{
let birthyear = IdCardNO.substring(6, 10);
let month = IdCardNO.substring(10, 12);
let day = IdCardNO.substring(12, 14);
let age = yearfull - Number(birthyear);
let genderValue = IdCardNO.substring(16, 17);
let gender = (Number(genderValue) % 2 == 0 ? "F" : "M"); // M--男 F--女
let genderCn = (Number(genderValue) % 2 == 0 ? "女" : "男"); // M--男 F--女
info.age = age.toString()
info.gender = gender
info.genderCn = genderCn
info.status = "200"
info.message = "身份证号解析完成"
}
if (IdCardNO.length == 15)//15位身份证号处理
{
let birthDay = "";
birthDay = IdCardNO.substring(6, 12);
birthDay = "19" + birthDay;
birthDay = birthDay.substring(0, 4);// + "-" + birthDay.substring(4, 6) + "-" + birthDay.substring(6)
let age = yearfull - Number(birthDay);//年龄
let gender = parseInt(birthDay.substring(14, 1), 10) % 2 ? "F" : "M";// M--男 F--女
let genderCn = parseInt(birthDay.substring(14, 1), 10) % 2 ? "女" : "男";// M--男 F--女
info.age = age.toString()
info.gender = gender
info.genderCn = genderCn
info.status = "200"
info.message = "身份证号解析完成"
}
return info
}
//18位
console.log(
getInfoByIdcard("332001199812152811")
)
//18位
console.log(
getInfoByIdcard("36220119999999282x")
)
//15位
console.log(
getInfoByIdcard("382301199999992")
)
console