吉他和弦自定义标签简单解析器

时间:2018-04-05 15:13:45

标签: javascript jquery css parsing markdown

我使用markdown存储带和弦的歌词,效果很好。     https://codepen.io/rrob/pen/GxYgOP 使用*作为标记<em>进行和弦,并使用css进行定位。

但现在我想要它在演示文稿中并且markdown解析在那里很复杂。 我尝试使用 str.replace 插入标记,但我无法关闭标记。

text text *chord* text text 

替换为:

text text <em>chord<em> text text 

我当然需要:

text text <em>chord</em> text text 

请问您是否知道一些解析自定义标签的简单解决方案? Javascript / Jquery。

2 个答案:

答案 0 :(得分:4)

您可以使用Regex来达到您的要求。您可以捕获*个字符以及它们之间的字符,然后将*替换为<em>个标记。像这样:

&#13;
&#13;
var input = 'text text *chord* text text *chord* text';
var output = input.replace(/\*(.*?)\*/g, '<em>$1</em>');

console.log(output);
&#13;
&#13;
&#13;

鉴于你的Codepen示例,完整的东西看起来像这样:

&#13;
&#13;
$('.chords').html(function(i, html) {
  return html.replace(/\*(.*?)\*/g, '<em>$1</em>');
});
&#13;
body {
  white-space: pre-line
}

em {
  line-height: 2.3em;
  position: relative;
  color: red;
  top: -1em;
  display: inline-block;
  width: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="chords">
  You *Emi*stood before creation
  Eternity within *A*Your hands
  You *G*spoke all li*D*fe into motion
  My *A*soul now to *Fdur*stand
</div>
<div class="chords">
  My *A*soul now to *Fdur*stand
  You *G*spoke all li*D*fe into motion
  Eternity within *A*Your hands
  You *Emi*stood before creation
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

查看以下功能。它迭代字符串中的每个字符,并在需要时用<em></em>替换'*'。

/**
 * parse function parse the input raw string and replaces the
 * the star(*) with <em> and </em> where needed.
 * @returns Returns the replaced string.
 */
function parse(str) {
    var ret = ""; // initialize the string.

    for (var x = 0; x < str.length; ++x) {
        if (str[x] == '*') { // The opening.
            ret += "<em>";
            ++x;

            for(; x < str.length; ++x) {
                if (str[x] == '*') { // and the ending is here.
                    ret += "</em>";
                    break;
                } else {
                    ret += str[x];
                }
            }
        } else {
            ret += str[x];
        }
    }

    return ret;
}

console.log(parse("Hello *JS*")); // outputs 'Hello <em>JS</em>

var element = document.querySelector('.chords');
element.innerHTML = parse(element.innerText);
相关问题