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
"您無法使用正規表示式解析[HTML]。[...]您是否嘗試過使用[HT]ML而是解析器?「™
(可以在下面的程式碼片段中找到更簡潔的版本)
嘗試一下:
'; console.log(replaceTextBrWithDiv(content));
這是我在尋求(更短的)正規表示式解決方案之前的嘗試: