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 );
Copy codeThe 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 );
}