设置汉字占2字节,英文字母1字节

80 阅读1分钟
 <input id="inp" />
 let inp = document.getElementById('inp')
 inp.addEventListener('input',()=>{
   console.log(inp.value.gblen())
})
 
  String.prototype.gblen = function() {
    let len = 0;
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) {
            len += 2;
        } else {
            len++;
        }
    }
    return len;
};