项目开发中会遇到一些常见的功能,为了方便调用,将其封装,以下列举了本人开发中重用的一些工具,后期将继续补充
对手机号中间4位进行加密处理
export const encryptionPhone = function (val) {
let reg = /(\d{3})\d*(\d{4})/
return val.replace(reg, "$1****$2")
}
判断年份是否为闰年
export const isLeapYear = function (year) {
return (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? true : false
}
判断字符串是否为同一字符
export const isStringSome = function (str) {
let reg = /^(.)\1*$/
return reg.test(str)
}
根据身份证号获取出生日期和性别、年龄(周岁)
/**
* 根据身份证号获取出生日期和性别、年龄(周岁)
* @param {String} idCardNo 身份证号
* @returns 返回出生日期、性别、年龄
*/
export const getBirthdayAndSexAndAgeByIDCardNo = function (idCardNo) {
let date = new Date()
let currentYear = date.getFullYear()
let currentMonth = date.getMonth() + 1
let currentDay = date.getDate()
let info = {}
let birthday = (idCardNo.length === 18) ? idCardNo.slice(6, 14) : idCardNo.slice(6, 12)
// 18位身份证,提取第17位, 15位身份证提取最后一位
let order = (idCardNo.length === 18) ? idCardNo.slice(-2, -1) : idCardNo.slice(-1)
info.birthDay = (idCardNo.length === 18) ? ([birthday.slice(0, 4), birthday.slice(4, 6), birthday.slice(-2)]).join('-') : (['19' + birthday.slice(0, 2), birthday.slice(2, 4), birthday.slice(-2)]).join('-')
/**
* 性别
* 0 代表女性
* 1 代表男性
*/
info.sex = (order % 2 === 0 ? 0 : 1)
let birthdayYear = (idCardNo.length === 18) ? birthday.slice(0, 4) : '19' + birthday.slice(0, 2)
let birthdayMonth = (idCardNo.length === 18) ? birthday.slice(4, 6) : birthday.slice(2, 4)
let birthdayDay = birthday.slice(-2)
if (currentYear == birthdayYear) {
info.age = 0
} else {
age = currentYear - birthdayYear - 1 > 0 ? currentYear - birthdayYear - 1 : 0
if (birthdayMonth <= currentMonth && birthdayDay <= currentDay) {
info.age = ++age
}
}
return info
}
根据证件有效期起期获取办证时的年龄以及证件有效期
/**
* 根据身份证号以及证件有效期的起期获取办证时的年龄以及证件有效期
* @param {String} idCardNo 身份证号
* @param {String} certificateValidityStartDate 证件有效期起期,格式为2021-10-10
* @returns 返回办证时年龄以及正确的证件有效期
*/
export const getAgeAndCertificateValidity = function (idCardNo, certificateValidityStartDate) {
let info = {}
let date = new Date(certificateValidityStartDate)
let currentYear = date.getFullYear()
let currentMonth = date.getMonth() + 1
let currentDay = date.getDate()
let birthday = (idCardNo.length === 18) ? idCardNo.slice(6, 14) : idCardNo.slice(6, 12)
let birthdayYear = (idCardNo.length === 18) ? birthday.slice(0, 4) : '19' + birthday.slice(0, 2)
let birthdayMonth = (idCardNo.length === 18) ? birthday.slice(4, 6) : birthday.slice(2, 4)
let birthdayDay = birthday.slice(-2)
if (currentYear == birthdayYear) {
info.age = 0
} else {
age = currentYear - birthdayYear - 1 > 0 ? currentYear - birthdayYear - 1 : 0
if (birthdayMonth <= currentMonth && birthdayDay <= currentDay) {
info.age = ++age
}
}
if (age < 16) {
info.certificateValidity = '5年'
} else if (age >= 16 && age <= 25) {
info.certificateValidity = '10年'
} else if (age >= 26 && age <= 45) {
info.certificateValidity = '20年'
} else if (age >= 46) {
info.certificateValidity = '长期'
}
return info
}