How do I use JavaScript regex to search for anything but an instance?

advertisements

I am using JavaScript regex and would like to strip HTML tags out of a string except for one situation.

Let's take this string for example:

"<a>link me</a>
 <p class="highlight">paragraph</p>
 <replace meta="data"></replace>"

I would like to use string replace to transform it into: (all HTML tags are stripped except for <[/?]replace[.*]>) "link me paragraph <replace meta="data"></replace>"

The regex for removing all tags would be:

html = String(html).replace(/<[^>]+>/gm, '');

How would one go about placing the exception for <replace> and </replace> in there?


Use negative lookahead:

/(?!<\/?replace)<[^>]+>/gm

The (?!<\/?replace) negative lookahead asserts that <[^>]+> cannot match if it's a replace opening or closing tag.

Regex101

var str = `<a>link me</a>
 <p class="highlight">paragraph</p>
 <replace meta="data">DO NOT REPLACE</replace>`;

var re = /(?!<\/?replace)<[^>]+>/gm;

document.querySelector('pre').textContent = str.replace(re, '');
<pre></pre>