我想这很简单,但我正在努力应对以下情况:
字符串(HTML 作为文本传递):
text<br>text<br><ul><li>text</li></ul><br>
现在我需要将每个 text<br> 替换为 <div>text</div>
除非文本位于 <li>/<ul> 内。
.replace(/(.*?)<br>/g, '<div>$1</div>')
这工作正常,但如何防止 <ul><li>text</li></ul><br> 被替换?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
"您无法使用正则表达式解析 [HTML]。[...]您是否尝试过使用 [HT]ML而是解析器?“™
(可以在下面的代码片段中找到更简洁的版本)
function replaceTextBrWithDiv(html) { // Create an element that acts as a parser const parser = document.createElement('div'); parser.innerHTML = html; // Modify an array-like when iterating over it may cause some issues. // Copy it first. const childNodes = [...parser.childNodes]; // Index-based iterating for (let index = 0; index ) index++; } } return parser.innerHTML; }尝试一下:
console.config({ maximize: true }); function replaceTextBrWithDiv(html) { const parser = document.createElement('div'); parser.innerHTML = html; parser.childNodes.forEach((node, index, nodes) => { const nextNode = nodes[index + 1]; if (node instanceof Text && nextNode instanceof HTMLBRElement) { const div = document.createElement('div'); div.appendChild(node); nextNode.replaceWith(div); } }); return parser.innerHTML; } const content = 'text
text
'; console.log(replaceTextBrWithDiv(content));
这是我在寻求(更短的)正则表达式解决方案之前的尝试:
const dFrag = document.createDocumentFragment(); str.textContent.split('').forEach(substr => { const div = document.createElement('div'); let ul; if (!substr) { substr = '
'; } div.innerHTML = substr; ul = div.querySelector('ul'); if (ul) { dFrag.appendChild(ul); } else { dFrag.appendChild(div); } }); str.innerHTML = ''; str.appendChild(dFrag);