LoginSignup
3
1

More than 5 years have passed since last update.

カクヨム記法の変換処理を実装する

Last updated at Posted at 2018-12-27

小説投稿サイトのカクヨムさんには、小説中の文章を装飾できるカクヨム記法というものがあります。
このカクヨム記法をHTML表現に変換するライブラリを作ってみました。

カクヨム記法について

特殊な記法をすることでルビと傍点を付けられるというものですね。
HTMLとしては<ruby><em>に変換します。
面倒なのは漢字判定が必要になるところですが、Unicodeの漢字範囲を調べて正規表現で実現できます。

このユーティリティを作っている最中に文字列を...で展開すると文字の配列に展開できるという発見をしました。...でオブジェクトを展開するのはよく見ますがこんな使い方もあるとは。JavaScriptは奥が深いですね。。。

const DOT_REGEX = /《《([^\n]{1,50}?)》》/g
const RUBY_REGEX = /[||]([^\n]{1,50}?)([^\n]{1,20}?)》/g
const KANJI_RUBY_REGEX = /([\u2e80-\u2fdf\u3005\3007\303b\u4e00-\u9faf\u3400-\u4dbf\uf900-\ufaff]{1,50}?)([^\n]{1,20}?)》/g

module.exports = function transformKakuyomuNotation (text) {
  text = text.replace(DOT_REGEX, function (match, p1){
    const text = [...p1].map(a => `<span>${a}</span>`).join('')
    return `<em class="emphasis">${text}</em>`
  })
  text = text.replace(RUBY_REGEX, function (match, p1, p2){
    return `<ruby><rb>${p1}</rb><rt>${p2}</rt></ruby>`
  })
  text = text.replace(KANJI_RUBY_REGEX, function (match, p1, p2){
    return `<ruby><rb>${p1}</rb><rt>${p2}</rt></ruby>`
  })
  return text
}

NPMパッケージも公開しています。

npm install @exco/kakuyomu-notatio
3
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
3
1