Guitar chords custom tag simple parser

Im using markdown to store chord lyrics and it works great.   https://codepen.io/rrob/pen/GxYgOP Using * for a tag <em>for chords and position it using css.

But now I want it to be in the presentation, and the markdown parsing there is complicated. I am trying to insert a tag with str.replace , but I cannot close the tag.

text text *chord* text text 

replaced by:

text text <em>chord<em> text text 

and of course I need:

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

Pls do you know some simple solution for parsing custom tags? Javascript / jQuery.

+4
source share
2 answers

Regex , . * , * <em>. - :

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

console.log(output);

Codepen, :

$('.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>
+4

. "*" <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);
+1

Source: https://habr.com/ru/post/1695822/


All Articles