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

Source: Internet
Author: User

Other do not know whether is usable, anyway the first certainly can use

Compute string Length (1 characters in English, 2 characters in Chinese) method one: [JavaScript] View plaincopy the code to see that it derives from my code slice 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: [JavaScript] View plaincopy on the code to see that the snippet is derived to my Code piece 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: [JavaScript] View plaincopy the code to see the snippet derived from the code slice var jmz = {}; Jmz. GetLength = function (str) {///<summary> Gets the actual length of the string, Chinese 2, English 1</summary>///<param name= "str" > to get  
 Length of 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;  
};   
Method four: [JavaScript] View plaincopy The code slice to derive my code slice var l = str.length;   
var blen = 0;   
For (i=0 i<l; i++) {if (Str.charcodeat (i) & 0xff00)!= 0) {Blen + +;   
} Blen + +; Method Five: Replace the double-byte with two single-byte and then get the length [JavaScript] View plaincopy the code to see the snippet derived to my code slice Getblen = function (str) {if (str = =  
    NULL) return 0;  
    if (typeof str!= "string") {str = "";  
Return Str.replace (/[^\x00-\xff]/g, "a"). Length;  
 }




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.