このページはコミュニティーの尽��で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

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(" ") を使ってテキストを単語に分割する場合、テキストのロケールが単語間の空白を使用しない場合(すなわち、日本語、中国語、タイ語、ラオス語、クメール語、ミャンマー語などの場合)、正しい結果を得ることはできません。

js
const str = "吾輩は猫である。名前はたぬき。";
console.table(str.split(" "));
// ['吾輩は猫である。名前はたぬき。']
// この 2 文をきちんと分割できていません。
js
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

ブラウザーの互換性

関連情報