Calculate the length of a string written in js and the Chinese character is in utf8 format. The specific implementation is as follows. If you are interested, refer to method 1 below:
The Code is as follows:
Function byteLength (str ){
Var byteLen = 0, len = str. length;
If (! Str) return 0;
For (var I = 0; I ByteLen ++ = str. charCodeAt (I)> 255? 2: 1;
Return byteLen;
}
Note: byteLength (str)
Parameters:
String str: string to calculate the length of a byte (2 bytes for non-ASCII characters)
Method 2:
JS gets the actual length of the string!
Add another small item today! A programmer often uses the string length detection method, because the original length of JavaScript is the same as that of Chinese and English. Therefore, you need to determine and obtain the actual length of the string.
The Code is as follows:
Function GetLength (str ){
///
Returns the actual length of the string, which is Chinese 2 and English 1.
/// String to be obtained
Var realLength = 0, len = str. length, charCode =-1;
For (var I = 0; I <len; I ++ ){
CharCode = str. charCodeAt (I );
If (charCode> = 0 & charCode <= 128) realLength + = 1;
Else realLength + = 2;
}
Return realLength;
};
Run the Code:
Alert (GetLength ('test ceshiceshi ));
Method 3: test failed
The Code is as follows:
Function getByteLen (val ){
Var len = 0;
For (var I = 0; I <val. length; I ++ ){
If (val [I]. match (/[\ u4e00-\ u9fa5]/ig )! = Null)
Len + = 2;
Else
Len + = 1;
}
Return len;
}
Method 4:
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;
}