Using JavaScript to compute the number of bytes used to store strings under UTF-8 _javascript tips

Source: Internet
Author: User
Lately it's been tangled up with JavaScript.

A problem with this is that the character set of the database is UTF-8, and you want to use JavaScript on the page to verify that the text you enter uses UTF-8 storage to occupy the byte length. The JavaScript string object has a length attribute, but this computes the number of characters, not the number of bytes (the problem is always over and over, remember when playing Delphi, you have to write a program to calculate the number of characters in the string, Because the length of the string in Delphi is the number of bytes ... )。 One way to be lazy is to set the maximum length in the validation code to 1/3 of the length of the corresponding field in the database, but that's not exactly the right thing to do.

So find a way to judge in JavaScript the number of string bytes stored under UTF-8, search the web for a lot of documentation about Unicode introductions, and most importantly, the storage length for character-encoded values:

UCS-2 Code (16) UTF-8 byte stream (binary)
0000-007f 0xxxxxxx (1 bytes)
0080-07FF 110xxxxx 10xxxxxx (2 bytes)
0800-FFFF 1110xxxx 10xxxxxx 10xxxxxx (3 bytes)

So the code is as follows:
[
Copy Code code as follows:

function Mbstringlength (s) {
var totallength = 0;
var i;
var charcode;
for (i = 0; i < s.length; i++) {
CharCode = S.charcodeat (i);
if (CharCode < 0x007f) {
Totallength = totallength + 1;
else if ((0x0080 <= charcode) && (charcode <= 0x07ff)) {
Totallength + 2;
else if ((0x0800 <= charcode) && (charcode <= 0xffff)) {
Totallength + 3;
}
}
alert (totallength);
return totallength;
}

In fact, the characters between 0x0080 to 0X07FF are rarely used in actual user input.

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.