Home > Web Front-end > JS Tutorial > body text

Javascript multiple ways to get the number of bytes in a string_javascript tips

WBOY
Release: 2016-05-16 18:51:54
Original
1327 people have browsed it

There are many methods, here are two:
The first one: (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 <= 0xff9f)) {
length = 1;
} else {
length = 2;
}
}
return length;
}

Second: (via escape( ) method and then judge after encoding)
Copy code The code is 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 of writing: completely speechless!
Copy code The code is as follows:

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
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template