Parse html string and append new div before every heading

I have a variable who contain html return as a string coming from an API so something like this :

const myHTML = "<h2>Lorem</h2><p>ipsupm</p><h3>second header</h3><h3>third header !!</h3>"

How can I parse it and add a div like "<div className="separator"></div>" before every headings whether it’s an h1, h2 or h3

Thanks in advance 🙂

Answer

One way to go is:

  1. use a RegExp to add the separator div before every heading (<h[1-6]>)
  2. create a div and set its innerHTML to the new HTML string
  3. append the new div to the body

// 0. Original HTML string
const myHTML = "<h2>Lorem</h2><p>ipsupm</p><h3>second header</h3><h3>third header !!</h3>"

// 1. use a RegExp to add the separator div before every heading
const newHTML = myHTML.replace(/(<h[1-6]{1}>)/g, '<div class="separator"></div>$1');

// 2. create a div and set its innerHTML to the new HTML string
const container = document.createElement('div');
container.innerHTML = newHTML;

// 3. append the new div to the body
document.querySelector('body').append(container);
.separator {
  height: 2px;
  width: 100%;
  background-color: #efefef;
}

If you want to exclude <h1> headings, you simply change

const newHTML = myHTML.replace(/(<h[1-6]{1}>)/g, '<div class="separator"></div>$1');

to

const newHTML = myHTML.replace(/(<h[2-6]{1}>)/g, '<div class="separator"></div>$1');

or any other range of headings (you got the idea).