<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>Intl.Segmenter 浏览器分词</title> </head> <body> <textarea class="txt1" rows="5" placeholder="浏览器中文分词"></textarea> <textarea class="txt2" rows="10" placeholder="分词结果"></textarea> </body> </html>
body { margin: 0; padding: 1em; } textarea { width: 100%; }
var domTxt1 = document.querySelector('.txt1'); var domTxt2 = document.querySelector('.txt2'); domTxt1.addEventListener('input', function () { if (Intl.Segmenter) { var segm = new Intl.Segmenter('cn', { granularity: 'word' }); var vals = Array.from(segm.segment(this.value)); domTxt2.value = vals.map(x => x.segment).join('\n'); console.debug(vals) } else { domTxt2.value = "该浏览器不支持 Intl.Segmenter"; console.debug(domTxt2.value) } })