Hi, I would like help creating a regex that replaces all html tags, but when the ending div and the beginning div are next to each other, it adds a space, like
This<b>is</b> <div>a</div><div>test</div>
This is a test
My current regex is /(<([^>] )>)/ig which will replace all html tags but I want to know whenever there is a closing div and the following opening div How to add a space to each other.
I tried replacing the valid html with /(<([^>] )>)/ig but I need help with the spacing of the divs when they are next to each other
P粉2960800762024-04-03 10:33:20
JS has built-in support for HTML parsing. Use this instead:
function getSpaceSeparatedText(html) { // Create an element and use it as a parser let parser = document.createElement('div'); parser.innerHTML = html; const result = []; for (const node of parser.childNodes) { // Get the trimmed text const text = node.textContent.trim(); // If text is not empty, add it to result if (text) { result.push(text); } } return result.join(' '); }
try it:
console.config({ maximize: true }); function getSpaceSeparatedText(html) { let parser = document.createElement('div'); parser.innerHTML = html; const result = []; for (const node of parser.childNodes) { const text = node.textContent.trim(); if (text) { result.push(text); } } return result.join(' '); } const html = ` This isatest`; console.log(getSpaceSeparatedText(html));
sssccc