1024programmer Java GBK, UTF8 string actual length calculation function implemented by JavaScript_Basic knowledge

GBK, UTF8 string actual length calculation function implemented by JavaScript_Basic knowledge

As we all know, the length of strings in JS does not distinguish between Chinese and English characters. Each character counts as a length, which is different from the strlen() function in PHP. The strlen() function in PHP accumulates GBK Chinese characters by 2 and UTF-8 Chinese characters by 3 according to the character set.

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

Mainly to match the length range of the database. For example, a field in the GBK database is varchar(10), which is equivalent to the length of 5 Chinese characters, and one Chinese character is equal to the length of two letters. If it is a UTF8 database, the length of each Chinese character is 3.

After knowing the above principles, we can calculate the actual length of a string. If it is a GBK character set, add 2 when encountering Chinese, and if it is a UTF8 character set, add 3 when encountering Chinese
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 is Chinese, add 2 to the length
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 is Chinese, add 3 to the length
realLength += 3;
}
}
return realLength;
}

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/629653

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索