im使用markdown用和弦存储歌词,并且效果很好。 https://codepen.io/rrob/pen/gxygop使用 *用于和弦的标签<em>
,然后将其与CSS进行定位。
,但现在我希望在演示文稿中进行宣传和降级解析,这很复杂。我尝试使用 str.replace 插入标签,但我无法关闭标签。
text text *chord* text text
替换为:
text text <em>chord<em> text text
当然需要:
text text <em>chord</em> text text
PLS您知道这样的简单解决方案,用于解析这样的自定义标签吗?javascript/jquery。
您可以使用Regex实现所需的目标。您可以捕获*
字符以及它们之间的字符,然后用<em>
标签替换*
。这样的东西:
var input = 'text text *chord* text text *chord* text';
var output = input.replace(/*(.*?)*/g, '<em>$1</em>');
console.log(output);
给定您的编码示例,完整的东西看起来像这样:
$('.chords').html(function(i, html) {
return html.replace(/*(.*?)*/g, '<em>$1</em>');
});
body {
white-space: pre-line
}
em {
line-height: 2.3em;
position: relative;
color: red;
top: -1em;
display: inline-block;
width: 0;
}
<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>
查看以下功能。它迭代字符串中的每个字符,并在需要的情况下用<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);