JavaScript computes the byte length of a string

Source: Internet
Author: User

When doing a front-end validation form, it is sometimes necessary to detect the byte length of a string to ensure that its byte length does not exceed the maximum allowable length for the corresponding field in the database table.

No nonsense, on the way

1. We usually encounter the situation is Chinese + English, so you can judge the Unicode encoding value of each character, greater than 255, for Chinese, byte should be larger than English 1 bytes:

1 functionByteLength (str) {2     varBytelen = str.length, Len =str.length, I;3      for(i = 0;i<len;i++){4         if(Str.charcodeat (i) > 255){5bytelen++;6         }7     }8     returnBytelen;9}

Note that the number of bytes corresponding to Chinese characters may vary depending on the character encoding used.

2. Solve different encoding, Chinese characters corresponding to the number of bytes of the problem, mainly for utf-16:

1 //Utf-8 is a variable-length Unicode encoding format that corresponds to 1~4 bytes per character2 //Most of the utf-16 use two byte encoding, encoding exceeds 65535 (00ffff) using 4 bytes3 functionbytelength (str, charset) {4     varTotal = 0,5 CharCode,6 I,7Len =Str.length,8 Bytelen,9CharSet = CharSet? Charset.tolowercase (): ";Ten     if(CharSet = = = ' Utf16 ' | | charset = = ' utf-16 '){ One          for(i = 0;i<len;i++){ A             if(Str.charcodeat (i) <= 0xFFFF){ -Bytelen + = 2; -}Else{ theBytelen + = 4; -             } -         } -}Else{ +          for(i = 0;i<len;i++){ -             if(Str.charcodeat (i) <= 0x007f){ +Bytelen + = 1; A}Else if(Str.charcodeat (i) <= 0x07ff){ atBytelen + = 2; -}Else if(Str.charcodeat (i) <= 0xFFFF){ -Bytelen + = 3; -}Else{ -Bytelen + = 4; -             } in         } -     } to     returnBytelen; +}

Refer to "JavaScript Framework Design"

JavaScript computes the byte length of a string

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.