There are many methods, here are two:
The first one: (through the charCodeAt method of the String object)
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;
}
Second: (via escape( ) method and then judge after encoding)
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;
}
The third way of writing: completely speechless!
String.prototype.getBytesLength = function() {
return this.replace(/[^x00-xff]/gi, "--").length;
}
I like the third one, the above codes all passed the test
The code is simple and does not give test results
px
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn