


GBK, UTF8 string actual length calculation function implemented by JavaScript_Basic knowledge
May 16, 2016 pm 04:38 PMAs 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 GBK's 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 characters. If it is a UTF8 character set, add 3 when encountering Chinese characters.
GBK length calculation function:
// Actual length calculation 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:
// 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, add 3 to the length
realLength = 3;
}
}
Return realLength;
}

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to implement an online speech recognition system using WebSocket and JavaScript

Go language encoding analysis: UTF-8 and GBK comparison

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems

How to implement an online reservation system using WebSocket and JavaScript

How to use JavaScript and WebSocket to implement a real-time online ordering system

Simple JavaScript Tutorial: How to Get HTTP Status Code

JavaScript and WebSocket: Building an efficient real-time weather forecasting system

How to use insertBefore in javascript
