-3

I have an html root element looks like this:

<div>
    <span>first</span>
    second
    <span>third</span>
    fourth
<div>

Now i need to wrap third and fourth with span like others, So the result will be:

<div>
    <span>first</span>
    <span>second</span>
    <span>third</span>  
    <span>fourth</span>
</div>
Faid
  • 554
  • 1
  • 5
  • 18
  • I guess you want this done with regex according to the tag? Have you seen this https://stackoverflow.com/a/1732454/14055983 ? – JPDF Aug 09 '20 at 20:23

2 Answers2

1

If you are doing this the browser I would recommend you do not use regular expressions but instead use the DOM handling capabilites built into the browser. (There are good reasons for not using RegExp for parsing HTML, see this stackoverflow answer to get a first impression)

When you walk through the DOM tree you can use nodeType to distinguish between nodes that are Tags (called "element nodes") and nodes that only contain text.

  div = document.querySelector('div');
  for( let child of div.childNodes ) {
    if (child.nodeType == Node.TEXT_NODE && /\w/.test(child.data) ) {
      console.log("type", child.nodeType, "for", child.data);
      let newChild = document.createElement('span');
      newChild.textContent = child.data;
      div.replaceChild(newChild, child)
    }
  }

See this codepen

bjelli
  • 9,752
  • 4
  • 35
  • 50
0

Maybe something like this?

let html = `<div>
    <span>first</span>
    second
    <span>third</span>
    fourth
<div>`

const formatHTML = (html) => {
  return html
    .split(/\r?\n/)
    .map((item) => {
      item = item.trim();
      if (item === '<div>' || item.indexOf('<span>') > -1) {
        return item;
      } else {
        return `<span>${item}</span>`;
      }
    })
    .join('\n');
}

console.log(formatHTML(html));
callback
  • 3,981
  • 1
  • 31
  • 55