How to strip out HTML tags from a string using JavaScript?


We can strip out HTML tags from a string with JavaScript using the following examples −

  • Strip out HTML tags using Regex
  • Strip out HTML tags using InnerText

Strip out HTML tags using Regex

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

Strip out HTML tags using InnerText

Example

In this example, we will strip the HTML tags using innerText −

<!DOCTYPE html> <html> <title>Strip HTML Tags</title> <head> <script> var html = "<html><head></head><body><p>The tags stripped...<p</body></html>"; var div = document.createElement("div"); div.innerHTML = html; var text = div.textContent || div.innerText || ""; document.write(text) </script> </head> <body> </body> </html>

Output

Updated on: 22-Nov-2022

683 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements