Calculate string actual length in JavaScript

Source: Internet
Author: User

Knowing the above principles, we can calculate the actual length of a string, if the GBK character set encountered in Chinese plus 2, if the UTF8 character set encountered Chinese plus 3 can

Example (this is our common)

  code is as follows copy code

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.c Harcodeat (i);
        if (charcode >= 0 && charcode <= 128) Reallength + = 1;
        Else reallength + + 2;
   }
    return reallength;
};   

Execute code:

The code is as follows Copy Code

Alert (JMZ. GetLength (' Test test Ceshiceshi ');

Instance

GBK Length calculation function:

The code is as follows Copy Code

//GBK Character Set actual length calculation
function Getstrleng (str) {
    var reallength = 0;
    var len = str.length;
    var charcode =-1;
    for (var i = 0; i < len; i++) {
        charcode = str.ch Arcodeat (i);
        if (charcode >= 0 && charcode <= 128) { 
&NBSP;&NB sp;          reallength + + 1;
       }else{ 
            //If Chinese then length plus 2
            reallength + 2;
       }
   } 
    return reallength;
}

UTF8 Length calculation function:

The code is as follows Copy Code

//UTF8 Character Set actual length calculation
function Getstrleng (str) {
    var reallength = 0;
    var len = str.length;
    var charcode =-1;
    for (var i = 0; i < len; i++) {
        charcode = str.ch Arcodeat (i);
        if (charcode >= 0 && charcode <= 128) { 
&NBSP;&NB sp;          reallength + + 1;
       }else{ 
            //If Chinese then length plus 3
            reallength + 3;
       }
   } 
    return reallength;
}

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.