Calculate the actual length of GBK and UTF8 strings implemented by JavaScript _ basic knowledge

Source: Internet
Author: User
This article mainly introduces the calculation functions of the actual length of GBK and UTF8 strings implemented by JavaScript. For more information, see, each character is regarded as a length, which is not the same as the strlen () function in PHP. The strlen () function in PHP accumulates every 2 of GBK Chinese characters according to the character set, and accumulates every 3 of the Chinese characters of the UTF-8.

Some children's shoes may ask, why do we need to calculate the actual length?

The main purpose is to match the length range of the database. For example, if a field in the GBK database is varchar (10), the length is equivalent to five Chinese characters, and one Chinese character is equal to the length of two letters. For UTF8 databases, the length of each Chinese character is 3.

After learning the above principles, we can calculate the actual length of a string. If the GBK character set encounters a Chinese character plus 2, if the UTF8 Character Set encounters a Chinese character plus 3.
GBK length calculation function:

The Code is as follows:


// Calculate the actual length of the GBK character set
Function getStrLeng (str ){
Var realLength = 0;
Var len = str. length;
Var charCode =-1;
For (var I = 0; I <len; I ++ ){
CharCode = str. charCodeAt (I );
If (charCode> = 0 & charCode <= 128 ){
RealLength + = 1;
} Else {
// If it is Chinese, the length is increased by 2
RealLength + = 2;
}
}
Return realLength;
}


UTF8 length calculation function:

The Code is as follows:


// 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. charCodeAt (I );
If (charCode> = 0 & charCode <= 128 ){
RealLength + = 1;
} Else {
// If it is Chinese, the length is increased by 3
RealLength + = 3;
}
}
Return realLength;
}

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.