As we all know, in JS, the length of a string is not divided into Chinese and English characters, and each character is counted as a length, which is different from the strlen() function in PHP. The strlen() function in PHP accumulates 2 Chinese characters in GBK according to the character set, and accumulates 3 Chinese characters in UTF-8.
Some children's shoes may ask, why do you need to calculate the actual length?
It is mainly to match the length range of the database. For example, a certain 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, each Chinese character has a length of 3.
After knowing the above principle, we can calculate the actual length of a string. If it is a GBK character set, add 2 in Chinese, and if it is a UTF8 character set, add 3 in Chinese.
GBK length calculation function:
The code copy 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, add 2 length
realLength += 2;
}
}
return realLength;
}
UTF8 length calculation function:
The code copy is as follows:
// Calculate the actual length of the 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 length
realLength += 3;
}
}
return realLength;
}