In order to solve this problem, yesterday I wrote a function that intercepts strings based on the number of bytes.
The specific use is very simple, just use it like String.subString(start, end). For example: var str = "Hey, I will caress you"; var str1 = str.subCHStr(2, 2); var str2 = str.subCHString(2, 4); alert(str1 " == " str2);
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 store them in 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; 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;
}
//Intercept string (intercepted from start byte length bytes)
String.prototype.subCHStr = function(start, length){
return this.subCHString(start, start length);
}