JavaScript regular expression to keep content containing specific words and replace everything else
P粉463824410
P粉463824410 2024-04-01 11:06:23
0
2
515

I guess this is simple, but I'm struggling with the following situation:

String (HTML passed as text):

text<br>text<br><ul><li>text</li></ul><br>

Now I need to replace each text<br> with <div>text</div> Unless the text is within <li>/<ul>.

.replace(/(.*?)<br>/g, '<div></div>')

This works fine, but how do I prevent <ul><li>text</li></ul><br> from being replaced?

P粉463824410
P粉463824410

reply all(2)
P粉488464731

"You cannot parse [HTML] using regular expressions. [...] Have you tried using [HT]ML instead with a parser? "

(A more concise version can be found in the code snippet below)

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;
}

try it:

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
  • text

'; console.log(replaceTextBrWithDiv(content));
sssccc
P粉336536706

Here's my attempt before going for a (shorter) regex solution:

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template