Strip HTML from Text JavaScript

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


Solution 1:

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.

Solution 2:

myString.replace(/<[^>]*>?/gm, '');

Solution 3:

Simplest way:

jQuery(html).text();

That retrieves all the text from a string of html.