JAVASCRIPT
Remove HTML Tags from String with Regex
Clean a string by removing all HTML tags using a regular expression in JavaScript, useful for sanitizing user-generated content.
const removeHtmlTags = (htmlString) => {
const htmlTagRegex = /<[^>]*>/g;
return htmlString.replace(htmlTagRegex, "");
};
const messyHtml = "<p>Hello <strong>World</strong>!</p> <a href='#'>Link</a>";
console.log(removeHtmlTags(messyHtml)); // "Hello World! Link"
const cleanText = "This is plain text.";
console.log(removeHtmlTags(cleanText)); // "This is plain text."
How it works: This JavaScript function employs a regular expression to remove all HTML tags from a given string. It finds any sequence starting with '<' and ending with '>', regardless of content in between (non-greedy match), and replaces it with an empty string, effectively stripping the tags from the text.