Strip HTML Tags from a String in JavaScript

Hello friends, in this trick, we will see how we can strip out all the HTML tags from a string using the javascript function.

To remove all the HTML tags from a string or text, we can use the javascript replace() function with a regular expression to identify the HTML tags.

We can also use the .textContent and .innerText properties of HTML DOM. These properties only return the text of any tag.

Let’s see the examples.

Strip HTML Tags with replace() Function

The replace() javascript function will strip out all HTML tags from a string. It will search for a matched value using a regular expression and return a new string with the replaced value. It will keep the original string as it is.

Output
Hey, I'm JavaScript.

Strip HTML Tags with .textContent and .innerText Properties

In this method, we will use the .textContent and .innerText properties of HTML DOM. This method is useful when you are creating a new element with javascript and wrapping the HTML code inside.

Then we can use these properties with that creating element variable to get the only text without any HTML tags. See the following example.

Output
Hey, I'm JavaScript.
Hey, I'm JavaScript.

Being Tricky 😉

Leave a Reply

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