Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to remove HTML tags from a string

Short answer

For simple markup, remove everything between angle brackets:

const html = '<p>Hello, <b>world</b>!</p>';
 
console.log(html.replace(/<[^>]*>/g, ''));

Output:

Hello, world!

In the browser: DOMParser

The browser can parse HTML itself. The textContent property returns only the text, and entities like &amp; turn into characters:

<script>
  const html = '<p>Tom &amp; <i>Jerry</i></p>';
  const doc = new DOMParser().parseFromString(html, 'text/html');
  document.body.append(doc.body.textContent); // Tom & Jerry
</script>

Common mistake

Removing tags does not make text safe for inserting with innerHTML. For that, escape the text or use textContent. Also, the regular expression leaves entities as they are:

console.log('<p>Tom &amp; Jerry</p>'.replace(/<[^>]*>/g, ''));

Output:

Tom &amp; Jerry

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.