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