The number and total number of Chinese characters in the regular check string

String regular

There is a need to check the string

  • Ensure that the input text is between 20 and 100 characters

analysis

  1. First of all, the characters occupied by Chinese characters and alphanumeric symbols are different during the input process.
  2. Therefore, the characters of Chinese characters are divided into 2 characters, and the others are all 1 characters.
  3. The sum of the addition is compared with the condition

Code

var str = "123字符串"
var hanReg = str.match(/[\u4e00-u9fa5]/g)
var hanCount =hanReg && hanReg.join("").length
var fontCount = str.length+hanCount
if (fontCount>100||fontCount<20) {
    
    
  alert('输入字符在20到100之间')
}

Guess you like

Origin blog.csdn.net/weixin_45176415/article/details/113952516