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 & turn into characters:
<script>
const html = '<p>Tom & <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 & Jerry</p>'.replace(/<[^>]*>/g, ''));Output:
Tom & JerryFunctions used in this recipe
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).