方法一 String.chartCodeAt() 返回相应字符的编码
原理:
遍历字符串的每个字符,利用chartCodeAt()获取相应字符编码code,
若code>=0 && code<=128,则长度+1,
否则长度+2.
String.prototype.GetLength = function() {
var realLength = 0, len = this.length, charCode = -1;
for (var i = 0; i < len; i++) {
charCode = this.charCodeAt(i);
if (charCode >= 0 && charCode <= 128) //重点
realLength += 1;
else
realLength += 2;
}
return realLength;
};
alert('mw测-=试12'.GetLength());
方法二 String.replace()正则替换
原理:
利用正则,全局检测,将中文转换成两位普通英文字符,再计算长度即可
//正则,将中文替换为两位英文字符
String.prototype.getLen = function(){
let str = this.replace(/[\u0391-\uFFE5]/g,"aa");
return str.length;
}
alert('mw测-=试12'.getLen());
参考链接 http://www.west999.com/cms/wiki/code/2018-07-20/40010.html