HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Strip HTML tags from text using plain JavaScript

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
tagsfromtextusinghtmlplainjavascriptstrip

Problem

How to strip off HTML tags from a string using plain JavaScript only, not using a library?

Solution

If you're running in a browser, then the easiest way is just to let the browser do it for you...

function stripHtml(html)
{
   let tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}


Note: as folks have noted in the comments, this is best avoided if you don't control the source of the HTML (for example, don't run this on anything that could've come from user input). For those scenarios, you can still let the browser do the work for you - see Saba's answer on using the now widely-available DOMParser.

Code Snippets

function stripHtml(html)
{
   let tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent || tmp.innerText || "";
}

Context

Stack Overflow Q#822452, score: 924

Revisions (0)

No revisions yet.