你能帮我讲一些正则表达吗? Razor编辑器和我想要在浏览内容时找到}
来设置新订单,但在我}}
时错过。
例如:
HTML文件
<tittle> {{ title }} </title> <-- it remains so
<script>
function name () {
some code...
} <-- go to new line
我的代码是:
var readableHTML = text.trim();
var lb = '\r\n';
var tab = "\u0020\u0020\u0020\u0020";
//Check for brackets
readableHTML = readableHTML.replace(new RegExp(" {", 'gi'), lb + tab + "{");
readableHTML = readableHTML.replace(new RegExp("({{([^{}]*)}})([^}])", 'gi'), lb + tab + "}"); <-- This is my wrong regex
答案 0 :(得分:0)
为什么不呢?
readableHTML = readableHTML.replace(new RegExp(" \{", 'gi'), lb + tab + "{");
readableHTML = readableHTML.replace(new RegExp(" \{{2}", 'gi'), lb + tab + "{{");
readableHTML = readableHTML.replace(new RegExp(" \}", 'gi'), lb + tab + "}");
readableHTML = readableHTML.replace(new RegExp(" \}{2}}", 'gi'), lb + tab + "}}");
答案 1 :(得分:0)
在涉及JavaScript时,您似乎只想在关闭大括号之前添加换行符。因此,我建议您将替换范围限制为script
标记。为此,您可以使用DOM解析器,这将有助于识别这些script
元素,并允许您更改其内容。
function replaceInScripts(html, find, replace) {
var doc = new DOMParser().parseFromString(html,"text/html");
Array.from(doc.querySelectorAll('script'), function(script) {
script.textContent = script.textContent.replace(find, replace);
});
return doc.documentElement.outerHTML;
}
// Sample data:
var html = `<html>
<head>
<title> {{ title }} </title>
</head>
<body>
<script>
function name () { return 1; }
<\/script>
</body>
</html>`;
// Call the function for replacing text within script elements only:
html = replaceInScripts(html, /(\S)\s*\}/g, '$1\n }');
// Output updated HTML:
console.log(html);
&#13;