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 オブジェクトは、ロケールに応じてテキストを区切ることができ、文字列から意味のある項目(書記素、単語、文)を取得することができます。
試してみましょう
const segmenterFr = new Intl.Segmenter("fr", { granularity: "word" });
const string = "Que ma joie demeure";
const iterator = segmenterFr.segment(string)[Symbol.iterator]();
console.log(iterator.next().value.segment);
// 予想される結果: 'Que'
console.log(iterator.next().value.segment);
// 予想される結果: ' '
コンストラクター
Intl.Segmenter()-
新しい
Intl.Segmenterオブジェクトを作成します。
静的メソッド
Intl.Segmenter.supportedLocalesOf()-
指定したロケールのうち、ランタイムのデフォルトロケールにフォールバックすることなく対応しているものを含む配列を返します。
インスタンスプロパティ
これらのプロパティは Intl.Segmenter.prototype で定義されており、すべての Intl.Segmenter インスタンスで共有されます。
Intl.Segmenter.prototype.constructor-
このインスタンスオブジェクトを作成したコンストラクター関数です。
Intl.Segmenterのインスタンスの場合、初期値はIntl.Segmenterコンストラクターとなります。 Intl.Segmenter.prototype[Symbol.toStringTag]-
[Symbol.toStringTag]プロパティの初期値は、文字列"Intl.Segmenter"です。このプロパティはObject.prototype.toString()で使用されます。
インスタンスメソッド
Intl.Segmenter.prototype.resolvedOptions()-
この
Intl.Segmenterオブジェクトの初期化時に計算されたロケールおよび粒度のオプションを反映したプロパティを持つ新しいオブジェクトを返します。 Intl.Segmenter.prototype.segment()-
この
Intl.Segmenterのインスタンスのロケールおよび粒度に従って文字列のセグメントを表す、新しい反復可能なSegmentsのインスタンスを返します。
例
基本的な使い方と String.prototype.split() との相違点
String.prototype.split(" ") を使ってテキストを単語に分割する場合、テキストのロケールが単語間の空白を使用しない場合(すなわち、日本語、中国語、タイ語、ラオス語、クメール語、ミャンマー語などの場合)、正しい結果を得ることはできません。
const str = "吾輩は猫である。名前はたぬき。";
console.table(str.split(" "));
// ['吾輩は猫である。名前はたぬき。']
// この 2 文をきちんと分割できていません。
const str = "吾輩は猫である。名前はたぬき。";
const segmenterJa = new Intl.Segmenter("ja-JP", { granularity: "word" });
const segments = segmenterJa.segment(str);
console.table(Array.from(segments));
// [{segment: '吾輩', index: 0, input: '吾輩は猫である。名前はたぬき。', isWordLike: true},
// etc.
// ]
仕様書
| Specification |
|---|
| ECMAScript® 2027 Internationalization API Specification # segmenter-objects |