為瞭解決這個問題昨天寫了根據位元組數截取字串的函數。
具體使用很簡單,跟String.subString(start, end)一樣使用就可。比如:var str = "誒必塞第衣愛撫即"; var str1 = str.subCHStr(2, 2); var str2 = str.subCHString(2, 4); alert(str1 + " == " + str2);
複製代碼 代碼如下:Code
//計算字串長度
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;
}
//將字串拆成字元,並存到數組中
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;
}
//判斷某個字元是否是漢字
String.prototype.isCHS = function(i){
if (this.charCodeAt(i) > 255 || this.charCodeAt(i) < 0)
return true;
else
return false;
}
//截取字串(從start位元組到end位元組)
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;
}
//截取字串(從start位元組截取length個位元組)
String.prototype.subCHStr = function(start, length){
return this.subCHString(start, start + length);
}