JAVASCRIPT
Remove HTML Tags from String
Learn how to effectively strip all HTML tags from a given string using a simple JavaScript regex pattern, useful for cleaning user-generated content for display.
function stripHtmlTags(htmlString) {
return htmlString.replace(/<[^>]*>/g, '');
}
// Example usage:
const dirtyHtml = '<p>Hello <b>World</b>!</p><span>Test</span>';
const cleanText = stripHtmlTags(dirtyHtml);
console.log(cleanText); // Output: "Hello World!Test"
How it works: This function uses a regular expression `/<[^>]*>/g` to find all occurrences of HTML tags. The pattern `/<` matches the opening angle bracket, `[^>]*` matches any character except `>` zero or more times, and `>` matches the closing angle bracket. The `g` flag ensures all matches are replaced, effectively stripping all HTML tags from the string.