Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 218
cp100 Avatar asked Sep 06 '25 03:09

cp100


2 Answers

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

like image 70
h2ooooooo Avatar answered Sep 07 '25 21:09

h2ooooooo


Try This

 function remove_tags(html)
 {
   var html = html.replace("<br>","||br||");  
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   html = tmp.textContent||tmp.innerText;
   return html.replace("||br||","<br>");  
 }
like image 43
Sudz Avatar answered Sep 07 '25 21:09

Sudz