JAVASCRIPT
Strip All HTML Tags from a String
Safely remove all HTML tags from a string to extract plain text content, useful for sanitization or display in environments that don't render HTML.
function stripHtmlTags(htmlString) {
// Regex to match any HTML tag (e.g., <p>, <div>, <a>, <span>, etc.)
const tagRegex = /<[^>]*>/g;
return htmlString.replace(tagRegex, '');
}
// Examples
const htmlContent = "<p>Hello, <strong>world</strong>!</p><br><span>How are you?</span>";
console.log(stripHtmlTags(htmlContent)); // Hello, world!How are you?
const complexHtml = "<div>User <img src='avatar.jpg' alt='avatar'> Input</div>";
console.log(stripHtmlTags(complexHtml)); // User Input
How it works: The `stripHtmlTags` JavaScript function uses a simple regular expression `/<[^>]*>/g` to find and remove all HTML tags from a given string. The pattern matches any character sequence starting with `<`, followed by zero or more characters that are not `>`, and ending with `>`. The `g` flag ensures all occurrences are replaced, resulting in a plain text string.