How to obtain the number of bytes of a string using JavaScript

Source: Internet
Author: User

The number of bytes of an English character is different from that of a Chinese character or Japanese character. If you directly use the Javascript Len function, the length of an English letter or Chinese character is considered to be 1. If the data needs to be stored in the database, the length cannot be effectively controlled, which may cause some risks. Two simple methods are used to calculate the length.

STR = escape ("Chinese ABC ,,");
Len = 0;
For (I = 0; I <Str. length; I ++, Len ++ ){
If (Str. charat (I) = "% "){
If (Str. charat (++ I) = "U "){
I + = 3;
Len ++;
}
I ++;
}
}
Alert (LEN );

STR = "Chinese characters ABC ,,";
Len = 0;
For (I = 0; I <Str. length; I ++ ){
Icode = Str. charcodeat (I );
If (icode> = 0 & icode <= 255) | (icode> = 0xff61 & icode <= 0xff9f )){
Len + = 1;
} Else {
Len + = 2;
}
}
Alert (LEN );

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.