How to remove HTML Tags with RegExp in JavaScript?


The regex will identify the HTML tags and then the replace() is used to replace the tags with null string. Let’s say we have the following HTML −

<html><head></head><body><p>The tags stripped...<p</body></html> 

We want to remove the above tags with Regular Expression. For that, we will create a custom function −

function removeTags(myStr) 

The myStr will have our HTML code for which we want to remove the tags −

function removeTags(myStr) { if ((myStr===null) || (myStr==='')) return false; else myStr = myStr.toString(); return myStr.replace( /(<([^>]+)>)/ig, ''); }

The call for the above function to remove tags goes like this −

document.write(removeTags('<html><head></head><body><p>The tags stripped...<p</body></html>'));;

Example

Let us now see the complete example −

<!DOCTYPE html> <html> <title>Strip HTML Tags</title> <head> <script> function removeTags(myStr) { if ((myStr===null) || (myStr==='')) return false; else myStr = myStr.toString(); return myStr.replace( /(<([^>]+)>)/ig, ''); } document.write(removeTags( '<html><head></head><body><p>The tags stripped...<p</body></html>'));; </script> </head> <body> </body> </html>

Output

Updated on: 22-Nov-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements