//透過身份證號計算年齡、性別、出生日期,userCard:身份證號的字串,不能是數字 function idCard(userCard) { // 身份證正規表示式 var re = /^\d{6}(((19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}([0-9]|x|X))|(\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}))$/; if (!re.test(userCard)) { // 測試身份證是否正確 console.log("身份證號碼格式有誤,請重新填寫!"); return false; } else { console.log('身份證正確') } var obj = { sex:'', age:'', } //獲取出生日期 obj.birth = userCard.substring(6, 10) + "-" + userCard.substring(10, 12) + "-" + userCard.substring(12, 14); //獲取性別 if (parseInt(userCard.substr(16, 1)) % 2 == 1) { obj.sex = "男"; } else { obj.sex = "女"; } //獲取年齡 var myDate = new Date(); var month = myDate.getMonth() + 1; var day = myDate.getDate(); var age = myDate.getFullYear() - userCard.substring(6, 10) - 1; if (userCard.substring(10, 12) < month || userCard.substring(10, 12) == month && userCard.substring(12, 14) <= day) { age++; } obj.age = age return obj; }