目的:计算字符串长度(英文占1个字符,中文汉字占2个字符)
方法一:
String.prototype.gblen = function() {
var len = 0;
for (var i=0; i if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {
len += 2;
} else {
len ++;
}
}
return len;
}
方法二:
function strlen(str){
var len = 0;
for (var i=0; i var c = str.charCodeAt(i);
//单字节加1
if ((c >= 0x0001 && c len++;
}
else {
len+=2;
}
}
return len;
}
方法三:
var jmz = {};
jmz.GetLength = function(str) {
///
获得字符串实际长度,中文2,英文1 ///
要获得长度的字符串
var realLength = 0, len = str.length, charCode = -1;
for (var i = 0; i charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode else realLength += 2;
}
return realLength;
};
方法四:
var l = str.length;
var blen = 0;
for(i=0; iif ((str.charCodeAt(i) & 0xff00) != 0) {
blen ++;
}
blen ++;
}
方法五:
把双字节的替换成两个单字节的然后再获得长度
getBLen = function(str) {
if (str == null) return 0;
if (typeof str != "string"){
str += "";
}
return str.replace(/[^\x00-\xff]/g,"01").length;
}