LoginSignup
1
1

More than 5 years have passed since last update.

Intl.v8BreakIterator で拡張書記素クラスターを扱う

Last updated at Posted at 2015-03-13

node.js や iojs で Intl を有効にしてビルドすると v8 独自実装の Intl.v8BreakIterator を利用できるようになります。

Mac OS X ですでにインストールされている ICU を利用する場合、ビルドオプションは次のように指定します。

pkg-config --modversion icu-i18n && ./configure --with-intl=system-icu

異体字セレクターを例に書記素クラスターの数を数えてみましょう。

コンストラクターの第1引数に言語タグを指定し、拡張書記素クラスター単位で扱うために第2引数のオブジェクトで character を指定します。

var str = '' + String.fromCodePoint(0xE0101) + '飾区';
console.log(3 === graphemeLength(str, ['ja-JP']));

var str2 = '' + String.fromCodePoint(0xE0101).repeat(10000) + '飾区';
console.log(3 === graphemeLength(str2, ['ja-JP']));

function graphemeLength(str, locales)
{
    var it = new Intl.v8BreakIterator(locales, {type: 'character'});
    it.adoptText(str);

    var length = 0;
    var previous = 0;
    var current = it.first();

    while (current !== -1) {

        current = it.next();

        if (current === -1) {
            break;
        }

        previous = current;
        ++length;
    }

    return length;
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1