There are a number of methods, two:
First: (Through the charCodeAt method of the string object)
Copy Code code as follows:
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 <=)) {
length = 1;
} else {
length = 2;
}
}
return length;
}
The second: (Through the Escape () method to encode after the judgement)
Copy Code code as follows:
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: completely silent!
Copy Code code as follows:
String.prototype.getBytesLength = function () {
Return This.replace (/[^\x00-\xff]/gi, "--"). Length;
}
I like the third Kind, the above code is tested through
Code is simple, no test results are given
Px