Javascript,typeScript根据身份证提取省市县、生日、性别。脱敏、校验等工具类(vue3)
    		       		warning:
    		            这篇文章距离上次修改已过443天,其中的内容可能已经有所变动。
    		        
        		                
                在JavaScript或TypeScript中,可以创建一个函数来解析身份证信息,提取省市县、生日和性别。以下是一个简单的函数实现:
function parseIdCardInfo(idCard) {
    if (!idCard || idCard.length !== 18) {
        throw new Error('Invalid ID card number');
    }
 
    const provinceCode = idCard.substring(0, 2);
    const cityCode = idCard.substring(2, 4);
    const countyCode = idCard.substring(4, 6);
 
    const birthdayYear = '19' + idCard.substring(6, 8);
    const birthdayMonth = idCard.substring(8, 10);
    const birthdayDay = idCard.substring(10, 12);
 
    const gender = parseInt(idCard.substring(16, 17)) % 2 === 0 ? '女' : '男';
 
    return {
        provinceCode,
        cityCode,
        countyCode,
        birthday: `${birthdayYear}-${birthdayMonth}-${birthdayDay}`,
        gender
    };
}
 
// 示例使用
try {
    const idCard = '110105198806051234';
    const info = parseIdCardInfo(idCard);
    console.log(info);
} catch (error) {
    console.error(error.message);
}这个函数首先检查身份证号码是否合法(18位),然后提取出省市县的代码,并结合后面的年月日信息来构造出生日期。最后根据身份证最后一位确定性别。
由于身份证号码的具体格式规则较为复杂,上述代码提取信息的方式是基于公众认可的格式。在实际应用中,可能需要根据最新的行政区划代码或其他规则来转换省市县的代码以获取更详细的信息。
此外,实际的生日和性别信息可能需要进一步的处理,比如进行年龄计算或者进行某些级别的隐私保护(比如隐去出生日期的具体年份),这些可以根据具体需求在函数中添加相应的逻辑。
评论已关闭