iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌊

[JS] Extracting Individual Characters from Strings Containing Extended Grapheme Clusters

に公開

When handling extended grapheme clusters in JavaScript, you use Intl.Segmenter. You can check if it's available by entering the following code.

> Intl.Segmenter
[Function: Segmenter]

Let's try converting a string into an array.

> segmenter = new Intl.Segmenter("ja", {granularity: "grapheme"})
Segmenter [Intl.Segmenter] {}

> str = "あいうえお"
'あいうえお'

> segment = segmenter.segment(str)
{}

for (s of segment) console.log(s.segment)
あ
い
う
え
お
undefined

You can also convert it to an array using Array.from.

>  Array.from(segment, v => v.segment)
[ 'あ', 'い', 'う', 'え', 'お' ]

By adding the length property, you can calculate the number of characters.

>  Array.from(segment, v => v.segment).length
5

Discussion