Categories
JavaScript Answers

How to remove HTML tags in JavaScript with regex?

Spread the love

Sometimes, we want to remove HTML tags in JavaScript with regex.

In this article, we’ll look at how to remove HTML tags in JavaScript with regex.

How to remove HTML tags in JavaScript with regex?

To remove HTML tags in JavaScript with regex, we use a regex that matches HTML tags with content.

For instance, we write

const regex = /(<([^>]+)>)/gi;
const body = "<p>test</p>";
const result = body.replace(regex, "");

to match all tags in a case insensitive manner with /(<([^>]+)>)/gi.

The g flag finds all matches.

And the i flag matches text in a case insensitive manner.

And then we call body.replace to match all the tags and replace them with empty strings.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *