JavaScript GBK UTF8 string actual length calculation function

  • 2020-03-30 03:46:07
  • OfStack

As you all know, string length in JS is not in both Chinese and English characters, each character is a length, which is different from the strlen() function in PHP. The strlen() function in PHP adds up the Chinese characters of GBK by 2, and the Chinese characters of utf-8 by 3, depending on the character set.

Some children's shoes may ask, why calculate the actual length?

It is mainly to match the length range of the database. For example, a field of GBK database is varchar(10), which is equivalent to the length of 5 Chinese characters, and a Chinese character is equal to the length of two letters. If the database is UTF8, the length of each character is 3.


Related articles: