How to remove HTML tags from a string using JavaScript
π
December 23, 2021
πJavaScript
In this short article, we will show you how to remove HTML tags from a string using JavaScript. There are many ways to strip out HTML tags from text but here we will look at two popular methods.
Checkout more articles on JavaScript
- Detect a mobile device using JavaScript
- Download a file using JavaScript
- Verify an image URL in JavaScript
- console methods in JavaScript
- Get the current date time of other countries
Ways to remove HTML tags from a string
1. Using regular expression
In the first method, we will use the Regular Expression to remove the HTML tags from the given string. Refer to the following code snippet to get the output.
function stripHTML(myString) {
return myString.replace( /(<([^>]+)>)/ig, '');
}
stripHTML(`<h1>Follow Clue Mediator</h1>`);
// Output: Follow Clue Mediator
2. Using DOM element
In the other methods, we will create a HTML element and use the `.textContent` property to return the plain text. The `.innerText` property does the same thing as `.textContent` property.
function stripHTML(myString) {
let el = document.createElement("div");
el.innerHTML = myString;
return el.textContent || el.innerText || "";
}
stripHTML(`<h1>Follow Clue Mediator</h1>`);
// Output: Follow Clue Mediator
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! π