Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How JavaScript calculates characters in a string

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report