我正在尝试构建一个个人降价编辑器。我几乎完成了摊牌库的源代码的启发。有关标题定义的以下部分是其中之一,使我陷入困境了几天:
.replace(/^(#)[ t]*(.+?)[ t]*n/gm,"<h1>$2<h1>");
在在线Regex测试仪中进行测试时,正则是很好。有任何线索为什么它不按预期工作?它是浏览器版本问题(我现在正在使用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
-->
`
由于您正在使用可编辑的div
,因此innerHTML
不包含新行,而是<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>