Knowing the above principles, we can calculate the actual length of a string, if the GBK character set encountered in Chinese plus 2, if the UTF8 character set encountered Chinese plus 3 can
Example (this is our common)
code is as follows |
copy code |
var jmz = {}; Jmz. GetLength = function (str) { ///<summary> gets 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.c Harcodeat (i); if (charcode >= 0 && charcode <= 128) Reallength + = 1; Else reallength + + 2; } return reallength; }; |
Execute code:
The code is as follows |
Copy Code |
Alert (JMZ. GetLength (' Test test Ceshiceshi '); |
Instance
GBK Length calculation function:
The code is as follows |
Copy Code |
//GBK 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.ch Arcodeat (i); if (charcode >= 0 && charcode <= 128) { &NBSP;&NB sp; reallength + + 1; }else{ //If Chinese then length plus 2 reallength + 2; } } return reallength; } |
UTF8 Length calculation function:
The code is as follows |
Copy Code |
//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.ch Arcodeat (i); if (charcode >= 0 && charcode <= 128) { &NBSP;&NB sp; reallength + + 1; }else{ //If Chinese then length plus 3 reallength + 3; } } return reallength; } |