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