Home > Tips & Tricks > Strip HTML Tags from a String in JavaScript

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 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment