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

Source: Internet
Author: User

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

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;

}

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.