How to remove all HTML tags from a string using JavaScript?

April 27, 2021 - 2 min read

To remove all HTML tags from a string, we can use the replace() string method in JavaScript.

TL;DR

// string with html tags
const str = "<div><h1>Hello World!</h1></div>";

// remove all html tags from string
str.replace(/(<([^>]+)>)/gi, ""); // Hello World

For example, let' say we have a string with some HTML tags in them like this,

// string with html tags
const str = "<div><h1>Hello World!</h1></div>";

Our goal is to remove the div, h1, etc tags present in the string. So let's use the replace() string method and pass:

  • a regex expression of /(<([^>]+)>)/ig as the first argument which will remove all the tags such as <> and </> and text inside it.
  • and an empty string as the second argument to say that we just want to replace the matched characters with an empty string.

It can be done like this,

// string with html tags
const str = "<div><h1>Hello World!</h1></div>";

// remove all html tags from string
const strWithoutHTmlTags = str.replace(/(<([^>]+)>)/gi, "");

console.log(strWithoutHTmlTags); // Hello World!

And we have successfully removed all HTML tags from the string. 😃

See the above code live in JSBin

Feel free to share if you found this useful 😃.