数式のある記事をKibelaのフォーマットからはてなブログのフォーマットに変換

約1年前にはてなブログを始めた時に、数式の書き方がわからなくて試行錯誤していました。(このときの記事→ はてなブログでのMarkdownでの数式の書き方 その2

私は下書きにKibelaのサービスを使っています。Kibelaは数式を書くのも比較的わかりやすいです。

そこで、Kibelaのフォーマットからはてなブログのフォーマットに変換する、簡易的なスクリプトを書きました。

  • インラインの数式は $$$$ で囲む
  • ブロックの数式は ```math``` で囲む

  • インラインの数式は [tex: \displaystyle] で囲む
  • ブロックの数式は <pre class="math">[tex: \displaystyle]</pre> で囲む

に変換します。

たまにエスケープ処理で変換に失敗しているときがありますが、以下のスクリプトを実用的に使っています。

HTML/JavaScriptのコード

<!DOCTYPE html>
<html>
<head>
<title>kibela-to-hatena</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>

$(function(){
  $("#src").focus(function() {
    $("#src").select();
  });
  $("#dst").focus(function() {
    $("#dst").select();
  });
  $("#convertBtn").click(function() {
    var str = $("#src").val();

    function replaceInline(match, p1, off, str) {
      p1 = p1.replace(/\^/g, "\\^");
      p1 = p1.replace(/_/g, "\\_");
      return "[tex: \\displaystyle " + p1 + "]";
    }

    function replaceBlock(match, p1, off, str) {
      p1 = p1.replace(/\]/g, "\\]");
      return "<pre class=\"math\">[tex: \\displaystyle\n" + p1 + "\n]</pre>\n";
    }

    str = str.replace(/\$\$(.+?)\$\$/g, replaceInline);
    str = str.replace(/(?<=\n)```math\n(.+?)\n```\n/sg, replaceBlock);
    str = str.replace(/(?<=\n)```([a-z]*)\n(.+?)\n```\n/sg, "<pre class=\"$1\">\n$2\n</pre>\n");

    $("#dst").val(str);
  });
});

</script>
</head>
<body>

<div>
  <textarea id="src"></textarea>
</div>

<div>
  <input id="convertBtn" type="button" value="↓変換">
</div>

<div>
  <textarea id="dst"></textarea>
</div>

</body>
</html>

このHTMLを適当なブラウザで開くと使えます。

以下のURLで公開しました。

https://suzuki-navi.github.io/suzuki-navi-converter/

サンプル

Kibelaでのソース

 インライン $$ e^{i\pi} = -1 $$

 ブロック

 ```math
 \begin{align}
 e^x &= \sum_{n=0}^\infty \frac{x^n}{n!} = -1 \\
 x &= \sigma
 \end{align}
 ```

はてなブログでのソース

 インライン [tex: \displaystyle  e\^{i\pi} = -1 ]

 ブロック

 <pre class="math">[tex: \displaystyle
 \begin{align}
 e^x &= \sum_{n=0}^\infty \frac{x^n}{n!} = -1 \\
 x &= \sigma
 \end{align}
 ]</pre>

はてなブログでの見た目

インライン  \displaystyle  e^{i\pi} = -1

ブロック

 \displaystyle
\begin{align}
e^x &= \sum_{n=0}^\infty \frac{x^n}{n!} = -1 \\
x &= \sigma
\end{align}