通过正则表达式制作降价标题符号

时间:2016-12-23 13:48:41

标签: javascript regex replace

我正在尝试建立一个个人降价编辑器。受showdown库的源代码启发很多,我几乎完成了任务,但有些代码奇怪地没有按预期工作。关于标题定义的以下部分是其中一个让我陷入困境的日子:

.replace(/^(#)[ \t]*(.+?)[ \t]*\n/gm,"<h1>$2<h1>");

an online regex tester中测试时,正则表达式似乎很好。任何线索为什么它不能按预期工作?这是浏览器版本问题(我现在正在使用FF 36.0.1 )?

修改即可。这是产生问题的最小示例 `

<!DOCTYPE html>
<html>
    <body>
    <div id="result" style="display:inline-block; width:45%; height:85vh; float:left; border:1px solid #555555;">Result</div>
    <button type="button"  onclick="compile();">Compile !</button>
    <div id="source" style="display:inline-block; width:45%; height:85vh; border:1px solid #555555;" contenteditable="true">Enter Code ...</div>    

        <script>
        var sourceContent, resultContent;
        function compile(){
            sourceContent=document.getElementById("source").innerHTML;
            resultContent=sourceContent.replace(/^(#)[ \t]*(.+?)[ \t]*\n+/gm,"<h1>$1</h1>");
            document.getElementById("result").innerHTML=resultContent;
        }
        </script>
    </body>
</html>


<!--
tested with:

#title 1
ok
# title 2
ok
#  title 3 #
ok
-->

`

1 个答案:

答案 0 :(得分:1)

由于您使用的是可编辑的divinnerHTML不包含新行,只有<br> s,这就是您的正则表达式不适合的原因。你可以使用textareas:

<!DOCTYPE html>
<html>
    <body>
    <div id="result" style="display:inline-block; width:45%; height:85vh; float:left; border:1px solid #555555;">Result</div>
    <button type="button"  onclick="compile();">Compile !</button>
    <textarea id="source" style="display:inline-block; width:45%; height:85vh; border:1px solid #555555;" contenteditable="true">Enter Code ...</textarea>    

        <script>
        var sourceContent, resultContent;
        function compile(){
            sourceContent=document.getElementById("source").value;
            resultContent=sourceContent.replace(/^(?:#)\s*(.+?)[ \t]*$/gm,"<h1>$1</h1>");
            document.getElementById("result").innerHTML=resultContent;
        }
        </script>
    </body>
</html>

或者稍微调整你的正则表达式:

<!DOCTYPE html>
<html>
    <body>
    <div id="result" style="display:inline-block; width:45%; height:85vh; float:left; border:1px solid #555555;">Result</div>
    <button type="button"  onclick="compile();">Compile !</button>
    <div id="source" style="display:inline-block; width:45%; height:85vh; border:1px solid #555555;" contenteditable="true">Enter Code ...</div>    

        <script>
        var sourceContent, resultContent;
        function compile(){
            sourceContent=document.getElementById("source").innerHTML;
          console.log(sourceContent);
            resultContent=sourceContent.replace(/(<br>(?: \/)?)?(?:#)\s*(.+?)[ \t]*(<br(?: \/)?>)/gm,"$1<h1>$2</h1>$3");
            document.getElementById("result").innerHTML=resultContent;
        }
        </script>
    </body>
</html>