Js two ways to determine whether a character is a Chinese character


Sometimes it is necessary to determine whether a character is a Chinese character or not, for example, when the user enters a content containing Chinese and English, it is necessary to determine whether it exceeds the specified length. There are usually two ways to do this with Javascript.

**1. Use regular expressions **

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  <title>js Determine whether a character is a Chinese character </title>
  <style type="text/css">
      .content{
          width:350px;
          overflow:hidden;
          border:1px solid #ddd;
      }
  </style>
<script language="javascript" type="text/javascript">
  function CheckChinese(obj,val){    
  var reg = new RegExp("[\u4E00-\u9FFF]+","g");
  if(reg.test(val)){    
       alert(" Unable to input Chinese characters! "); 
       var strObj = document.getElementById(obj); 
       strObj.value = ""
       strObj.focus();         
  }      
  }
</script>
</head>
<body>
  <div class="content">
      <div> Test characters: <input id="test" type="text" onblur="CheckChinese('test',this.value)" /> </div>
  </div
</body>
</html>

2. Use Unicode character range

The following method is used to calculate the length of the input string. Otherwise the string length will be 1.

  function chkstrlen(str)
  {
    var strlen = 0;
    for(var i = 0;i < str.length; i++)
    {
      if(str.charCodeAt(i) > 255) //If it's a Chinese character, add 2 to the length of the string
        strlen += 2;
      else 
        strlen++;
    }
    return   strlen;
  }