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 < childNodes.length; index++) {
const node = childNodes[index];
const nextNode = childNodes[index + 1];
if (node instanceof Text && nextNode instanceof HTMLBRElement) {
const div = document.createElement('div');
// Remove text node from parser and append it to div
div.appendChild(node);
nextNode.replaceWith(div);
// Skip next node (i.e. <br>)
index++;
}
}
return parser.innerHTML;
}
3条答案
按热度按时间yizd12fk1#
这是我在要求一个(更短的)正则表达式解决方案之前的尝试:
jtw3ybtb2#
"You can't parse [HTML] with regex. [...] Have you tried using an [HT]ML parser instead?" ™
(更简洁的版本可以在下面的片段中找到)
试试看:
q7solyqu3#
如果你更喜欢使用正则表达式,可以使用 /(?!<li.?>)(?!)(?!<ul.?>)(?!)(.?)
/g*
但是如果您切换到HTML解析器来轻松地导航和修改HTML内容的结构,那就更好了