最終更新日 2025-04-26

マクロ内で「文字列」を「文字配列」へと分解する(サロゲートペアを考慮して分解)

標準機能だけで処理できる

実は、これはJavaScriptの標準機能に含まれてますので、難しくありません。

jsmode "WebView2\\" + currentmacrofilename;

js {
    debuginfo(2);
    function main() {

        let totalText = gettotaltext();
        
        // セグメンター  'ja' は言語タグ、'grapheme' はテキスト要素(字)を分割する単位
        const segmenter = new Intl.Segmenter('ja', { granularity: 'grapheme' });

        // ここに格納する。
        let charArray = []

        // グラフェムイテレータ
        function* graphemeIterator(text) {
            for (const segment of segmenter.segment(text)) {
                yield segment.segment; // 各segmentのsegmentプロパティには字が含まれる
            }
        }

        for (const grapheme of graphemeIterator(totalText)) {
            charArray.push(grapheme);
        }
        
        console.log(JSON.stringify(charArray));
        
    }
    
    hidemaru.setTimeout(main, 0);
}