内含95个工具函数 前端大佬都在使用的JavaScript工具函数宝典( 八 )

82 校验是否为中国大陆第二代居民身份证校验规则:
共18位,最后一位可为X(大小写均可)
不能以0开头
出生年月日会进行校验:年份只能为18/19/2*开头,月份只能为01-12,日只能为01-31
function isIDCard(str){return /^[1-9][0-9]{5}(18|19|(2[0-9]))[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}[0-9Xx]$/.test(str);}83 校验是否为中国大陆邮政编码参数value为数字或字符串
校验规则:

  • 共6位,且不能以0开头
function isPostCode(value){return /^[1-9][0-9]{5}$/.test(value.toString());}84 校验两个参数是否完全相同,包括类型校验规则:
  • 值相同,数据类型也相同
function same(firstValue,secondValue){return firstValue=https://www.isolves.com/it/cxkf/yy/js/2020-08-05/==secondValue;}85 校验字符的长度是否在规定的范围内校验规则:
  • minInt为在取值范围中最小的长度
  • maxInt为在取值范围中最大的长度
function lengthRange(str,minLength,maxLength=9007199254740991) {return Boolean(str.length >= minLength && str.length <= maxLength);}86 校验字符是否以字母开头校验规则:
  • 必须以字母开头
  • 开头的字母不区分大小写
function letterBegin(str){return /^[A-z]/.test(str);}87 校验字符是否为纯数字(整数)校验规则:
  • 字符全部为正整数(包含0)
  • 可以以0开头
function pureNum(str) {return /^[0-9]*$/.test(str);}function anysicPunctuation(str){if(!str) return null;let arr = str.split('').map(item => {return item = '\' + item;});return arr.join('|');}function getPunctuation(str){return anysicPunctuation(str) || '\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?';}function getExcludePunctuation(str){let regexp = new RegExp(`[${anysicPunctuation(str)}]`,'g');return getPunctuation(' ~`!@#$%^&*()-_+=[]{};:"',<.>/?'.replace(regexp,''));}88 返回字符串构成种类(字母,数字,标点符号)的数量LIP缩写的由来:L(letter 字母) + I(uint 数字) + P(punctuation 标点符号)
参数punctuation的说明:
  • punctuation指可接受的标点符号集
  • 若需自定义符号集,例如“仅包含中划线和下划线”,将参数设置为"-_"即可
  • 若不传值或默认为null,则内部默认标点符号集为除空格外的其他英文标点符号:~`!@#$%^&*()-_+=[]{};:"',<.>/?
function getLIPTypes(str,punctuation=null){let p_regexp = new RegExp('['+getPunctuation(punctuation)+']');return /[A-z]/.test(str) + /[0-9]/.test(str) + p_regexp.test(str);}89 校验字符串构成的种类数量是否大于或等于参数num的值 。通常用来校验用户设置的密码复杂程度 。校验规则:
  • 参数num为需要构成的种类(字母、数字、标点符号),该值只能是1-3 。
  • 默认参数num的值为1,即表示:至少包含字母,数字,标点符号中的1种
  • 若参数num的值为2,即表示:至少包含字母,数字,标点符号中的2种
  • 若参数num的值为3,即表示:必须同时包含字母,数字,标点符号
  • 参数punctuation指可接受的标点符号集,具体设定可参考getLIPTypes()方法中关于标点符号集的解释 。
function pureLIP(str,num=1,punctuation=null){let regexp = new RegExp(`[^A-z0-9|${getPunctuation(punctuation)}]`);return Boolean(!regexp.test(str) && getLIPTypes(str,punctuation)>= num);}90 清除所有空格function clearSpaces(str){return str.replace(/[ ]/g,'');}91 清除所有中文字符(包括中文标点符号)function clearCNChars(str){return str.replace(/[\u4e00-\u9fa5]/g,'');}92 清除所有中文字符及空格function clearCNCharsAndSpaces(str){return str.replace(/[\u4e00-\u9fa5 ]/g,'');}93 除保留标点符号集以外,清除其他所有英文的标点符号(含空格)全部英文标点符号为:~`!@#$%^&*()-_+=[]{};:"',<.>/?
参数excludePunctuation指需要保留的标点符号集,例如若传递的值为'_',即表示清除_以外的其他所有英文标点符号 。
function clearPunctuation(str,excludePunctuation=null){let regexp = new RegExp(`[${getExcludePunctuation(excludePunctuation)}]`,'g');return str.replace(regexp,'');}94 校验是否包含空格function haveSpace(str) {return /[ ]/.test(str);}95 校验是否包含中文字符(包括中文标点符号)


推荐阅读