JavaScript Answers

How to Remove HTML Tags in JavaScript with Regex?

Spread the love

We can use the string’s replace instance method to remove the tags from an HTML string.

For instance, we can write:

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

We use the /(<([^>]+)>)/ig to get all the open and closing tags in the string.

g indicates we get all matches of the pattern in the string.

Then we call replace with the regex and an empty string to remove the tags from the body.

Therefore, result is 'test' .

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.