Intl.Segmenter Splits Words Across Scripts

Tokenize Latin and CJK text into linguistic words with Intl.Segmenter word granularity and filter out spaces and punctuation using the isWordLike flag.

JavascriptData Integrity

Code

snippet
const enSegmenter = new Intl.Segmenter('en', { granularity: 'word' });
const zhSegmenter = new Intl.Segmenter('zh-CN', { granularity: 'word' });

function extractWords(segmenter, text) {
  return [...segmenter.segment(text)]
    .filter((entry) => entry.isWordLike)
    .map((entry) => entry.segment);
}

const enSample = "Don't panic: v2.4 shipped 12 fixes!";
const zhSample = '今天发布了新版 CLI 工具,支持快速校验。';

const enWords = extractWords(enSegmenter, enSample);
const zhWords = extractWords(zhSegmenter, zhSample);

console.log('en words:', enWords.length, JSON.stringify(enWords));
console.log('zh words:', zhWords.length, JSON.stringify(zhWords));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

en words: 6 ["Don't","panic","v2.4","shipped","12","fixes"]
zh words: 10 ["今天","发布","了","新版","CLI","工具","支持","快速","校","验"]

Execution breakdown — Intl.Segmenter Splits Words Across Scripts

The code’s whole job belongs to the function extractWords.

It builds and returns a fresh value rather than reusing its inputs.

Caveats

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

The entry-point signature is function extractWords(segmenter, text)

The file’s steps show up in the output as en words:, zh words:.

Key statements

const zhSegmenter = new Intl.Segmenter('zh-CN', { granularity: 'word' });
const enSegmenter = new Intl.Segmenter('en', { granularity: 'word' });
.map((entry) => entry.segment);

Interactive Tools for This Topic

FAQ

Does `extractWords` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `extractWords` at load time.