Get the App
SLTechnology News&Howtos  ›  Development  › 

How JavaScript calculates characters in a string

Shulou Source: shulou.com Published: 2022-06-01 05:03:43 09月29日 Update

This article mainly introduces how JavaScript calculates the characters in the string, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.

How to calculate characters in a string

You can use the length property.

Const word = "apple"; console.log (word.length) / / 5

But for Chinese, this method is not very reliable.

Const word = "?" Console.log (word.length) / / 2

Japanese Kanji? The return length is 2. Why? JS represents most characters as 16-bit code points. However, some characters are represented as two (or more) 16-bit code points, called proxy pairs. If you are using the length attribute, JS tells you how many code points are used. Therefore, hokke consists of two code points and returns the wrong value.

Then how to judge, using the deconstruction operation symbol (.)

Const word = "?" Const characters = [... word] console.log (characters.length) / / 1

This method works in most cases, but there are some extreme cases. For example, if you use emoticons, sometimes this length is wrong. If you really want to calculate the correct length of a character, you must decompose the word into Grapheme Clusters, which is beyond the scope of this article, and is not explained here.

Thank you for reading this article carefully. I hope the article "how to calculate characters in a string in JavaScript" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you to learn!

Tags: Characters codes articles strings two attributes situations methods more symbols errors length validity value interest words and at the same time friends extremes knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Apple Redmi Huawei Shulou Information