How JavaScript determines the length of a string (1 characters in English, 2 characters for Chinese characters)

Source: Internet
Author: User

Compute string Length (1 characters in English, 2 characters for Chinese characters)

Method One:

String.prototype.gblen = function () {    
    var len = 0;    
    for (var i=0 i<this.length; i++) {    
        if (this.charcodeat (i) >127 | | this.charcodeat (i) ==94) {    
             len + 2;    
         } else {    
             len + +;    
         }    
     }    
    return len;    
}

Method Two:

function strlen (str) {  
    var len = 0;  
    for (var i=0; i<str.length; i++) {   
     var c = str.charcodeat (i);   
    Single byte plus 1   
     if ((c >= 0x0001 && C <= 0x007e) | | (0xff60<=c && c<=0xff9f)) {   
       len++;   
     }   
     else {   
      len+=2;   
     }   
    }   
    return len;  
}

Method Three:

var jmz = {};  
Jmz. GetLength = function (str) {  
    ///<summary> gets the actual length of the string, Chinese 2, English 1</summary>  
    ///<param name= "str" > to get the length of the string </param>  
    var reallength = 0, Len = str.length, charcode =-1;  
    for (var i = 0; i < len; i++) {  
        charcode = str.charcodeat (i);  
        if (charcode >= 0 && charcode <= 128) Reallength + = 1;  
        else Reallength + + 2;  
    }  
    return reallength;  
};

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

Method Four:

var L = str.length;   
var blen = 0;   
For (i=0 i<l; i++) {   
if (str.charcodeat (i) & 0xff00)!= 0) {   
Blen + +;   
}   
Blen + +;   
}

Method Five:

Replace two bytes with two single-byte and then get the length

Getblen = function (str) {  
    if (str = null) return 0;  
    if (typeof str!= "string") {  
        str = "";  
    }  
    Return Str.replace (/[^\x00-\xff]/g, "a"). Length;
}

Author: csdn blog Micro WX Smile

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.