JS字符串--中英文长度统计
/**
* 方式一 耗时间
*/
function getStringLength(str){
var sStr,iCount,i,strTemp ;
iCount = 0 ;
sStr = str.split("");//拆分出每一个字符
for (i = 0 ; i < sStr.length ; i ++){
strTemp = escape(sStr[i]); //编码
if (strTemp.indexOf("%u",0) == -1){
iCount += 1 ;
}else{
iCount += 2 ;
}
}
return iCount ;
}
/**
* 方式二
*/
function getLen1( str) {
var totallength=0;
for (var i=0;i<str.length;i++){
var intCode=str.charCodeAt(i);
if (intCode>=0&&intCode<=128) {
totallength=totallength+1; //非中文单个字符长度加 1
}else{
totallength=totallength+2; //中文字符长度则加 2
}
}
return totallength;
}
/**
* 方式三 效率最高了
*/
function getLen2( str) {
//将中文替换成两个英文字符来统计
return str.replace(/[^\x00-\xff]/g,"aa").length;
}
![](https://files.cnblogs.com/files/yangw/zfb_hongb.gif)
![](https://files.cnblogs.com/files/yangw/wx_s.gif)
![](https://files.cnblogs.com/files/yangw/zfb_s.gif)
未经作者 https://www.cnblogs.com/xin1006/ 梦相随1006 同意,不得擅自转载本文,否则后果自负