Javascript gets several ways to get string bytes _javascript tips

Source: Internet
Author: User
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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.