<div> <br> 在所见即所得编辑器中从 到 的完美转换



我需要在所见即所得编辑器中清理HTML。输出不得包含任何<div>s。所有<div>元素都必须替换为<br>元素。此原始文本必须与经过净化的文本呈现相同。

到目前为止,这是我的尝试(注意输出中不需要的额外空白(——感谢Nimit的渲染容器:

let text = `<div>aoeu</div><div><ul><li>eu</li><li>a</li></ul><div><br></div></div><div>eu</div>`;
// let text = 'aoeu<ul><li>aoeu</li><ul><li>aoue</li></ul></ul><div><br></div></div></div><div><br></div><div><br></div><div><br></div><div>oe</div><div><ul><li>u</li></ul></div>'
document.getElementById("pre1").innerHTML = "<strong>With Div</strong> </br>" + text;
text = text
.replace(/<div><div>(.*)</div></div>/g, '<div>$1</div>') // meaningless directly double wrapped divs
.replace(/<div><br></div>/g, '<br>') // div with a br is only one newline
.replace(/<div>(?!<div>)(.*?)</div>/g, '$1<br>') // divs always make a newline after
document.getElementById("pre2").innerHTML = "<strong>Without Div</strong> </br>" + text;
.preContainer {
display:inline-block;
width:200px;
vertical-align:top;
}
.preContainer:first-child{
border-right:1px solid black;
}
<div class="preContainer"><pre id="pre1"></pre></div>
<div class="preContainer"><pre id="pre2"></pre></div>

所以基本上我似乎不知道如何完美地从<div>转换为<br>。非常感谢您的帮助。

我认为您可以使用下面的替换脚本来实现您的结果。

.replace("<div>", "<br>").replace("</div>", "");

检查下面的代码段,你可以检查两个pre,第二个pre没有任何div标签:

function showItInPre(text){
//let text = `aoeua<div><ul><li>oe</li><li>a</li><li>oeu</li></ul><div><br></div></div><div><br></div><div><br></div><div>aoe</div><div><ul><li>u</li></ul><div><br></div></div><div><br></div><div>u</div><div><div><br></div></div><div>o</div><div><ul><li>o</li><li>o</li><li>a</li><li><br></li></ul></div>`;
document.getElementById("pre1").innerHTML = "<strong>With Div</strong> </br>" + text;
text = text
.replace(/<div><br></div>/ig, '<br>')
.replace(/</div></div>/ig, '<br>')
.replace(/<div>/ig, "").replace(/</div>/ig, "<br>");
document.getElementById("pre2").innerHTML = "<strong>Without Div</strong> </br>" + text;
}
document.getElementById("testit").addEventListener("click", function(){showItInPre(document.getElementById("textarea").value)});
.preContainer {
display:inline-block;
width:200px;
vertical-align:top;
}
#pre1{
border-right:1px solid black;
}
#textarea {
width:500px; height:50px;
}
<div><textarea id="textarea"></textarea><button id="testit">Test</button></div>
<div class="preContainer"><pre id="pre1"></pre></div>
<div class="preContainer"><pre id="pre2"></pre></div>

最新更新