1、charCodeAt()方法
strObj.charCodeAt(index)方法:返回的是index位置的字符的Unicode编码,为整数。若index小于0或者大于字符串长度,返回NaN。使用该方法计算字符串的字符个数:
{优快云:CODE:function getLength(){
var str='',n=null;
for(var i=0;i<str.length;i++){
if(str.charCodeAt(i)>=0&&str.charCodeAt(i)<=256){
n+=2;
}else{
n+=1;
}
}
}
}
2、正则表达式
一般的中文字符集用[ \u4e00-\u9fa5]即可,若想要匹配多种类型汉字或者其他的特殊字符,可以用 [
\u2E80-\uFE4F]。
用法:var
len=str.match(/[\u4e00-\u9fa5]/); //可以返回含有中文字符的数组。
console.log(2*len.length); //即可得到汉字字符串的字符个数
顺便提一下charAt()方法与charCodeAt()方法的区别:
charAt(index)用法与charCodeAt()方法类似,他返回的是index位置的字符。若index小于0或者大于字符串长度,则返回的是一个空字符串。