JSFiddle - React, Tailwind, and code Playground

by Ankit Verma

JavaScript

let content = `
<h2>User generated Dynamic Data 1</h2>
    <h3>User generated text 1.1</h3>
    <h3>User generated text 1.2</h3>


<h2>User generated Dynamic Data 2</h2>
    <h3>User generated text 2.1</h3>
    <h3>User generated text 2.2</h3>
    <h3>User generated text 2.3</h3>
    
<h2>User generated Dynamic Data 3</h2>
    <h3>User generated text 3.1</h3>
    <h3>User generated text 3.2</h3>
`;

// -- find text between a <h2> tag
const stext = content.match(/(?<=<h2>).*(<\/h2>)|(?<=<h3>).*(?=<\/h3>)/g);
console.log('stext:: ', stext);

let output1 = '', output2 = '', count = 0;
stext.forEach(text => {
	if(text.indexOf('</h2>') > -1) {
		// -- every time a primary text is found update the user generated content. This will run 1 count behind the main counter
  	if(count > 0) {
    	content = content.replace(output1, `${output1}<button class="something" onclick="bubble_fn_add_headers({output1: '${output1}', output2: ${output2}});">Save</button>`)
    }
  	// -- this is for primary text
    output1 = text.replace('</h2>', '');
    output2 = ''; // -- resetting this
    count++;
  }
  else {
  	// -- this is for sub-text
    output2 += `${text}\n`; 
  }
});
content = content.replace(output1, `${output1}<button class="something" onclick="bubble_fn_add_headers({output1: '${output1}', output2: ${output2}});">Save</button>`)

document.querySelector('body').innerHTML = content;