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

rro*_*rob 5 javascript css markdown jquery parsing

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

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

text text *chord* text text 
Run Code Online (Sandbox Code Playgroud)

替换为:

text text <em>chord<em> text text 
Run Code Online (Sandbox Code Playgroud)

我当然需要:

text text <em>chord</em> text text 
Run Code Online (Sandbox Code Playgroud)

请问您知道一些解析这样的自定义标签的简单解决方案吗?JavaScript/Jquery。

Ror*_*san 5

您可以使用正则表达式来实现您的要求。您可以捕获*字符及其之间的字符,然后将其替换*<em>标签。像这样的东西:

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

console.log(output);
Run Code Online (Sandbox Code Playgroud)

鉴于您的 Codepen 示例,完整的内容将如下所示:

$('.chords').html(function(i, html) {
  return html.replace(/\*(.*?)\*/g, '<em>$1</em>');
});
Run Code Online (Sandbox Code Playgroud)
body {
  white-space: pre-line
}

em {
  line-height: 2.3em;
  position: relative;
  color: red;
  top: -1em;
  display: inline-block;
  width: 0;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)