Using regex to replace HTML in div and add spacing
P粉043432210
P粉043432210 2024-04-02 11:28:02
0
1
509

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粉043432210
P粉043432210

reply all(1)
P粉296080076

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 is 
a
test
`; console.log(getSpaceSeparatedText(html));
sssccc
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template