Intl.Segmenter() コンストラクター
Baseline
2024
Newly available
Since April 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Intl.Segmenter() コンストラクターは、ロケールに依存したテキスト分割を可能にする Intl.Segmenter オブジェクトを生成します。
試してみましょう
const segmenterFr = new Intl.Segmenter("fr", { granularity: "word" });
const string1 = "Que ma joie demeure";
const iterator1 = segmenterFr.segment(string1)[Symbol.iterator]();
console.log(iterator1.next().value.segment);
// Expected output: 'Que'
console.log(iterator1.next().value.segment);
// Expected output: ' '
構文
new Intl.Segmenter();
new Intl.Segmenter(locales);
new Intl.Segmenter(locales, options);
引数
locales省略可-
BCP 47 の言語タグを持つ文字列、またはそのような文字列の配列。引数
localesの一般的な形式と解釈については、Intlのページを参照してください。 options省略可-
以下のプロパティの一部または全部を持つオブジェクト。
granularity省略可-
文字列。使用可能な値は以下の通り。
"grapheme"(default)-
ロケールに応じた書記素クラスター(ユーザーが認識する文字)の境界で、入力を分割します。
"word"-
ロケールに応じた単語の境界で、入力を分割します。
"sentence"-
ロケールに応じた文の境界で、入力を分割します。
localeMatcher省略可-
使用するロケールマッチングアルゴリズム。使用できる値は以下の通り。
"best fit"(default)-
ランタイムは、ルックアップアルゴリズムの結果よりも適したロケールを選択する可能性があります。
"lookup"-
BCP 47 Lookup algorithm を使用して、
localesからロケールを選択します。localesに含まれる各ロケールについて、ランタイムは最初にサポートされるロケールを返します(場合によっては、サポートされるロケールを見つけるために、与えられたロケールタグのサブタグの制限を取り除きます。つまり、localesとして"de-CH"を指定すると、"de"はサポートされているが"de-CH"はサポートされていない場合、"de"を使用することになる可能性があります)。
返値
新しい Intl.Segments のインスタンスです。
例
>基本的な使い方
次の例は、日本語を使って文字列中の単語を数えるものです(String のメソッドで文字列を分割すると不正確な結果が得られます)。
const text = "吾輩は猫である。名前はたぬき。";
const japaneseSegmenter = new Intl.Segmenter("ja-JP", { granularity: "word" });
console.log(
[...japaneseSegmenter.segment(text)].filter((segment) => segment.isWordLike)
.length,
);
// text は '吾輩'|'は'|'猫'|'で'|'ある'|'。'|'名前'|'は'|'たぬき'|'。' と分割されるので、8 が記録されます。
仕様書
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification> # sec-intl-segmenter-constructor> |
ブラウザーの互換性
Loading…