Intl.Segmenter

Baseline 2024
新推出

自 ⁨2024 年 4 月⁩ 起,此功能可在最新的裝置和瀏覽器版本中執行。此功能可能不適用於較舊的裝置或瀏覽器。

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);
// Expected output: 'Que'

console.log(iterator.next().value.segment);
// Expected output: ' '

建構函式

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()

返回一個新的可迭代 Segments 例項,該例項根據此 Intl.Segmenter 例項的區域和粒度表示字串的片段。

示例

基本用法及與 String.prototype.split() 的區別

如果我們使用 String.prototype.split(" ") 來分割文字中的單詞,那麼如果文字的區域在單詞之間不使用空格(如日語、中文、泰語、寮國語、高棉語、緬甸語等),我們將無法獲得正確的結果。

js
const str = "吾輩は貓である。名前はたぬき。";
console.table(str.split(" "));
// ['吾輩は貓である。名前はたぬき。']
// The two sentences are not correctly segmented.
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.
// ]

規範

規範
ECMAScript® 2026 國際化 API 規範
# segmenter-objects

瀏覽器相容性

另見