js判断字符串长度,中文占两个字符

分析前言:

// \x00-\xff 是字符编码的范围,如果查过这个范围,就不是字母和数字了,   
//把全部符合\x00-\xff条件的字符用**替换,然后计算长度,即遇到一个中文就用**替换,计算为两位   
 var length = name.replace(/[^\x00-\xff]/g,"**").length;

方案1:

用js判断字符串的长度:

如:str=”中国”,alert(str.length),则提示长度为2。

做如下处理后:

str=str.replace(/[^\x00-\xff]/g, 'xx'),alert(str.length)则长度提示为4

方案2:

function strlen(str){
    var len = 0;
    for (var i=0; i<str.length; i++) { 
      var c = str.charCodeAt(i); 
      //单字节加1 
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
         len++; 
      } else { 
         len+=2; 
      }
    } 
    return len;
}

sample:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JS-TRING</title>
    <script type="text/javascript" >
        //方案1
        function wayOne(){
            var str = document.getElementById('tt').value;
            str=str.replace(/[^\x00-\xff]/g, 'xx');
            alert(str.length);
        }
        //方案2-01
        function wayTwo(){
            var str = document.getElementById('tt').value;
            alert(WidthCheck(str, 6));
        }
        //方案2-02
        function WidthCheck(s, n){
            var w = 0;
            for (var i=0; i<s.length; i++) {
               var c = s.charCodeAt(i);
               //单字节加1
               if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
                    w++;
               } else {
                    w+=2;
               }
            }
            if (w == n) {
                return true;
            }
            return false;
        }
    </script>
</head>
<body>
    <div style="margin:10px 0;">
        <form>
            <input type="text" id="tt" />
            <input type="button" value="wayOne" onclick="wayOne();" />
            <input type="button" value="wayTwo" onclick="wayTwo();" />
        </form>
    </div>
</body>
</html>
原文地址:https://www.cnblogs.com/tv151579/p/3033407.html