The actual length calculation function of GBK and UTF8 strings implemented by JavaScript

Source: Internet
Author: User
Tags character set

Mainly to match the length of the database, such as the GBK database a field is varchar (10), then the equivalent of 5 characters length, one Chinese character is equal to two letter length. If the database is UTF8, the length of each Chinese character is 3.

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

GBK Length calculation function:

  The code is as follows:

Calculation of actual length of 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's Chinese then length plus 2

Reallength + 2;

}

}

return reallength;

}

UTF8 Length calculation function:

  The code is as follows:

Calculation of actual length of UTF8 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's 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.