Remove html tags except <br> or <br/> tags with javascript

cp100 picture cp100 · May 23, 2013 · Viewed 24.8k times · Source

I want to remove all the html tags except <br> or <br/> tags from a string using javascript. I have seen many questions like this but their answers will remove all the html tags including <br> and <br/> tags.

Does anyone knows a regex to do this?

Answer

h2ooooooo picture h2ooooooo · May 23, 2013

Use a negative lookahead (by using a regex such as /<(?!br\s*\/?)[^>]+>/g):

var html = 'this is my <b>string</b> and it\'s pretty cool<br />isn\'t it?<br>Yep, it is. <strong>More HTML tags</strong>';
html = html.replace(/<(?!br\s*\/?)[^>]+>/g, '');

console.log(html); 
//this is my string and it's pretty cool<br />isn't it?<br>Yep, it is. More HTML tags

Demo