本文提供一段 JavaScript 代码,用于根据输入的 15 位或 18 位身份证号自动解析并生成对应的出生日期。通过获取输入框值,利用正则表达式提取年份和月份信息,并在页面中弹窗显示结果。代码包含完整的 HTML 结构及交互逻辑,可直接复制运行测试。
JavaScript 根据身份证号自动提取出生日期
本文介绍如何利用 JavaScript 实现根据身份证号自动提取出生日期的功能,并提供相关代码供参考。
具体运行效果如下图所示:

<!doctype>
<html>
<head>
<script type="text/javascript">
function dealCard(){
var birthday=getBirthday();
switch(birthday){
case 0:alert("Sorry,the program runs wrong!");break;
case 1:alert("You must be input again!");break;
default: alert("the birthday is"+birthday);break;
}
}
function getBirthday(){
var a=document.getElementById("card").value;
if(15==a.length || 18==a.length){
var left=a.length-12;
var right=a.length-4;
var b=a.slice(left,right);
if(8==b.length){
return b;
}
else return 0;
}
else return 1;
}
</script>
</head>
<body>
input <input type="text" id="card" height=20px width=40px/>
<br/>
<button type="button" onclick="dealCard()">please click it</button>
</body>
</html>
您可以直接复制以下代码进行运行测试:
希望这段关于 JavaScript 程序设计的示例能对您的学习有所帮助。