Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Created October 24, 2024 11:24
Show Gist options
  • Save manabuyasuda/7fd16dd918f7e1489a7b65aef13fce54 to your computer and use it in GitHub Desktop.
Save manabuyasuda/7fd16dd918f7e1489a7b65aef13fce54 to your computer and use it in GitHub Desktop.
文字列を受け取って正確に文字数を返す
/**
* 文字列の文字数を返します。
* @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