代码之家  ›  专栏  ›  技术社区  ›  rrob

吉他弦自定义标记简单分析器

  •  5
  • rrob  · 技术社区  · 7 年前

    我使用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 
    

    请你知道一些简单的解析自定义标签的方法吗? Javascript/Jquery。

    2 回复  |  直到 7 年前
        1
  •  5
  •   Rory McCrossan Hsm Sharique Hasan    7 年前

    您可以使用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>
        2
  •  2
  •   Mohit    7 年前

    查看以下函数。它迭代字符串中的每个字符,并将“*”替换为 <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);