JAVASCRIPT
Removing HTML Tags from a String
Learn to sanitize user-generated content or plain text by effectively stripping out all HTML tags using a simple regular expression in JavaScript.
function stripHtmlTags(htmlString) {
const htmlTagRegex = /<[^>]*>/g;
return htmlString.replace(htmlTagRegex, "");
}
// Example Usage:
const dirtyHtml = "<h1>Hello <b>World</b>!</h1><p>This is a paragraph.</p>";
console.log(stripHtmlTags(dirtyHtml)); // "Hello World!This is a paragraph."
const cleanText = "Just plain text.";
console.log(stripHtmlTags(cleanText)); // "Just plain text."
How it works: This JavaScript snippet provides a `stripHtmlTags` function that cleans a string by removing all HTML tags. It uses the regular expression `/<[^>]*>/g` to find any sequence starting with '<', followed by zero or more characters that are not '>', and ending with '>', then replaces all such occurrences with an empty string, effectively stripping the tags.