const regex = /(<h([1-3]{1})[^>]*?(?! id)(?:id=\"([^\"]*)\"[^>]*)?>)(.*)<\/h\2>|<!--nextpage-->/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(<h([1-3]{1})[^>]*?(?! id)(?:id=\\"([^\\"]*)\\"[^>]*)?>)(.*)<\\\/h\\2>|<!--nextpage-->', 'g')
const str = `<h1>Test</h1>
<h1 id="test">Test</h1>
<h2 test="testattr" id="id">Test</h2>
<h3 id="id" test="test">Test</h3>
<h3 test="test" id="test" test="test">TEST</h3>
<h4></h4>
test
sdlfkdslf
<table>
h1
<!--nextpage-->`;
const subst = `\1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions