Javascript 获取字符串字节数的多种方法
第一種:(通過String對象的charCodeAt方法)
String.prototype.getBytesLength = function() {
var length = 0;
for(i = 0;i < this.length; i++) {
iCode = this.charCodeAt(i);
if((iCode >= 0 && iCode <= 255) || (iCode >= 0xff61 && iCode <= 0xff9f)) {
length += 1;
} else {
length += 2;
}
}
return length;
}
第二種:(通過escape()方法轉編碼后判斷)
String.prototype.getBytesLength = function() {
var str = escape(this);
for(var i = 0, length = 0;i < str.length; i++, length++) {
if(str.charAt(i) == "%") {
if(str.charAt(++i) == "u") {
i += 3;
length++;
}
i++;
}
}
return length;
}
第三種寫法:徹底無語了!
function reallength(var) {
return this.replace(/[^\x00-\xff]/gi, "--").length;
}
轉載于:https://www.cnblogs.com/dodui/archive/2010/02/26/pengtao.html
總結
以上是生活随笔為你收集整理的Javascript 获取字符串字节数的多种方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: read函数的用法
- 下一篇: java美元兑换,(Java实现) 美元