Strip HTML from Text JavaScript

Bryan picture Bryan · May 5, 2009 · Viewed 674.6k times · Source

Is there an easy way to take a string of html in JavaScript and strip out the html?

Answer

Shog9 picture Shog9 · May 5, 2009

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.