JavaScript 正则匹配中文,中文符号,空格,全数字,以https:// 开头的url,用于各种场景的输入校验

业务场景1:
  密码输入框需要验证输入中文,中文符号,空格等情况,以便于给出错误提示
业务场景2:
  输入框只允许输入数字的情况
业务场景3:
  输入框允许输入均为数字或以https:// 开头的url的情况
备注:
  网上查阅的大部分JavaScript中文/中文符号/空格等正则匹配,在中文加一个英文或者数字都能校验通过,无法满足实际的校验需求,使用下面的字符串替换方法,并比对str替换前后的length,即可完成准确的实际校验需求
  var length = str.length
  // str为想要验证的字符串
  console.log('length====>>>>>',length)
  var chinese_length = str.replace(/[\u4e00-\u9fa5]/g,'').length
  // chinese_length为匹配到中文后并替换成''之后的str字符串长度,中间的正则匹配中文,例如str = 'te测试st',length = 6,chinese_length = 4,用于做后面的逻辑判断
  var space_length = str.replace(/\s/g,'').length
  // space_length 为匹配到字符串中间的空格后并替换成''之后的str字符串长度,中间的正则匹配字符串中间的空格,例如str = 'te st',length = 5,space_length = 4,用于做后面的逻辑判断
  // 注意如果str = ' tes t ',str首部和尾部均有空格的场景,可以考虑使用trim()进行删除,删掉头尾的空格后再进行操作,trim()使用方法自行查阅
  console.log('space_length ====>>>>>',space_length )
  var CN_punctuation_length = str.replace(
/[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/g,'').length
  // CN_punctuation_length 为匹配到字符串的中文符号后并替换成''之后的str字符串长度,中间的正则匹配字符串的常用的所有中文符号,例如str = 't。e【st',length = 6,CN_punctuation_length = 4,用于做后面的逻辑判断
  console.log('CN_punctuation_length ====>>>>>',CN_punctuation_length )
  if (length !== chinese_length) {
    throw new Error(`输入不合法,个人链接/个人代码禁止使用中文:${str}`)
  } else if (length !== CN_punctuation_length) {
    throw new Error(`输入不合法,个人链接/个人代码禁止使用中文符号:${str}`)
  } else if (length !== space_length) {
    throw new Error(`输入不合法,个人链接/个人代码禁止使用空格:${str}`)
  } else {
    if(/^\d+$/.test(str)){
      //此步骤判断是否str均为数字组成
      const code = str
    } else if (/(https):\/\/([\w.]+\/?)\S*/.test(str)){
      //此步骤判断是否str为https:// 开头的url
      const url = str
    } else {
      throw new Error(`输入不合法,请输入正确的个人链接/个人代码:${str}`)
    }

Computer science and software engineering have always been my passion

posted @ 2020-12-23 11:54  游弋在冷风中  阅读(1263)  评论(0)    收藏  举报