SwiftMango
SwiftMango

Reputation: 15284

How can I remove all HTML tags in a string except for a few?

For example I have a string

<p>
<div style="test">This is in a div</div>
</p>
<img src="">
<br>
final words

I would like to remove all tags except img and br so that the final string looks like:

This is in a div
<img src="">
<br>
final words

I tried using regex but I could not figure out how to do exceptions.

s.replace(/\<.+?\>/g, ""); //except certain ones?

Upvotes: 2

Views: 4254

Answers (2)

Marco Bonelli
Marco Bonelli

Reputation: 69336

The right code is:

s.replace(/\<(?!img|br).*?\>/g, "");

Example:

var s = "<div>This is in a div <img src=''><br> final words</div>";
console.log(s.replace(/\<(?!img|br).*?\>/g, ""));

> "This is in a div <img src=''><br> final words"

Upvotes: 6

lpg
lpg

Reputation: 4937

What about this small modification? It would ignore the ones starting with <i or <b ...

s.replace(/\<[^ib].+?\>/g, "");

Upvotes: -1

Related Questions