Created
October 24, 2024 11:24
-
-
Save manabuyasuda/7fd16dd918f7e1489a7b65aef13fce54 to your computer and use it in GitHub Desktop.
文字列を受け取って正確に文字数を返す
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 文字列の文字数を返します。 | |
* @param {string} str - カウントする文字列 | |
* @param {Intl.LocalesArgument} [locale='ja-JP'] - 使用するロケール(デフォルトは日本語) | |
* @returns {number} 文字数 | |
* @example | |
* getCountCharacters('こんにちは'); // 5 | |
* getCountCharacters('𩸽を買って❗️'); // 6 | |
*/ | |
export function getCountCharacters( | |
str: string, | |
locale: Intl.LocalesArgument = 'ja-JP', | |
): number { | |
// 書記素(文字の最小単位)ごとに分割する | |
const segmenter = new Intl.Segmenter(locale, { granularity: 'grapheme' }); | |
// 文字列を分割して、その長さを返す | |
return Array.from(segmenter.segment(str)).length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment