Method One:
Copy Code code as follows:
function ByteLength (str) {
var bytelen = 0, len = str.length;
if (!STR) return 0;
for (var i=0; i<len; i++)
Bytelen + = str.charcodeat (i) > 255? 2:1;
return bytelen;
}
Description: ByteLength (str)
Parameters:
String str: strings to compute byte length (2 bytes of non-ASCII characters)
Method Two:
JS gets the actual length of the string!
Add another little thing today! A programmer often uses the string length detection method, because the original length of JS in Chinese and English as a character of 1 length. So here we need to judge for ourselves and get the actual length of the string.
Copy Code code as follows:
function GetLength (str) {
<summary> get the actual length of the string, Chinese 2, English 1</summary>
<param name= "str" > to get the length of the string </param>
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;
};
Execute code:
Alert (getlength (' Test test Ceshiceshi) ";
Method Three: Did not pass the test at the moment
Copy Code code 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 Four:
GBK Length calculation function:
Copy Code code 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:
Copy Code code 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;
}