Sometimes it may be too long to display a text segment, affecting the Display Effect of our page. If it is only English, we can use the String. substring (start, end) function. However, we usually encounter both English and Chinese characters. The Chinese Character occupies 2 bytes. if the substring (start, end) intercepts a string, you will find that the number of Chinese characters after the truncation is the same as that after the English truncation, but the length is still a lot longer (depending on the number of characters) to solve this problem, I wrote a function that intercepts strings based on the number of bytes yesterday.
It is easy to use, just like String. subString (start, end. For example, var str = "cailove"; var str1 = str. subCHStr (2, 2); var str2 = str. subCHString (2, 4); alert (str1 + "=" + str2 );
The Code is as follows:
Code
// Calculate the string length
String. prototype. strLen = function (){
Var len = 0;
For (var I = 0; I <this. length; I ++ ){
If (this. charCodeAt (I)> 255 | this. charCodeAt (I) <0) len + = 2; else len ++;
}
Return len;
}
// Split the string into characters and coexist in the array
String. prototype. strToChars = function (){
Var chars = new Array ();
For (var I = 0; I <this. length; I ++ ){
Chars [I] = [this. substr (I, 1), this. isCHS (I)];
}
String. prototype. charsArray = chars;
Return chars;
}
// Determine whether a character is a Chinese character
String. prototype. isCHS = function (I ){
If (this. charCodeAt (I)> 255 || this. charCodeAt (I) <0)
Return true;
Else
Return false;
}
// Truncate the string (from the start byte to the end byte)
String. prototype. subCHString = function (start, end ){
Var len = 0;
Var str = "";
This. strToChars ();
For (var I = 0; I <this. length; I ++ ){
If (this. charsArray [I] [1])
Len + = 2;
Else
Len ++;
If (end <len)
Return str;
Else if (start <len)
Str + = this. charsArray [I] [0];
}
Return str;
}
// Truncate the string (The length byte is truncated from the start byte)
String. prototype. subCHStr = function (start, length ){
Return this. subCHString (start, start + length );
}