7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryで英数字にルビを振る

Last updated at Posted at 2017-03-16

サーバーから出力された英数字にルビを振って欲しいと依頼が来たが、結局実装することはなく、せっかくなので備忘録もかねて。

html
<p class="txt">HOGEHOGE123</p><!-- ここのテキストがサーバーから出力された文字列と仮定する -->
<ruby class="txt-kana"></ruby>
jQuery
$(function(){
    var txt = $('.txt').text();
    var kana = $('.txt-kana');
    // 英数字とルビを連想配列にする。
    var str = {
        "A": "えー",
        "B": "びー",
        "C": "しー",
        "D": "でぃー",
        "E": "いー",
        "F": "えふ",
        "G": "じー",
        "H": "えいち",
        "I": "あい",
        "J": "じぇー",
        "K": "けー",
        "L": "える",
        "M": "えむ",
        "N": "えぬ",
        "O": "おー",
        "P": "ぴー",
        "Q": "きゅー",
        "R": "あーる",
        "S": "えす",
        "T": "てぃー",
        "U": "ゆー",
        "V": "ぶい",
        "W": "だぶる",
        "X": "えっくす",
        "Y": "わい",
        "Z": "ぜっと",
        "0": "ぜろ",
        "1": "いち",
        "2": "",
        "3": "さん",
        "4": "よん",
        "5": "",
        "6": "ろく",
        "7": "なな",
        "8": "はち",
        "9": "きゅう"
    };

    for (var i = 0; i < txt.length; i++) {
        kana.append('<p>' + txt[i] + '</p>' + '<rt>' + str[txt[i]] + '</rt>');
    }
});

txt[i]にはHOGEHOGE123が以下のように順番に入る。

H
O
G
...

str["A"]のキーで、値の「えー」を取得できる。
str[txt[i]]とすると、順番に
str["H"]
str["O"]
str["G"] ...となるので、それぞれの値「えいち」「おー」「じー」...を出力する。

append()<ruby>に表示。
<ruby>はデフォルトだと、テキストの上に表示されるので、以下画像のようになる。

スクリーンショット 2017-03-16 10.36.14.png

最終的にすごい簡単なコードで実現できたが、やたらと時間がかかってしまい、ロジックの考え方がまだまだだなと認識させられたので自戒を込めて投稿。

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?