JS 获取字符串长度, 区别中英文

js 添加代码:

String.prototype.getBytes = function() {  
    var cArr = this.match(/[^\x00-\xff]/ig);  
    return this.length + (cArr == null ? 0 : cArr.length);  
}

使用方法:
  "dddZ红dddd白".getBytes ();

getBytes用正则表达式来判断字符串中包含汉字的个数,包含的汉字都放到数组cArr中,这样cArr的长度就是汉字的总数。getBytes方法返回length加上汉字数,就是总的字节数。

原文地址:https://www.cnblogs.com/henw/p/2134443.html