JAVASCRIPT
Remove HTML Tags from String Input
Sanitize user input by removing all HTML tags from a string using a regular expression, preventing potential cross-site scripting (XSS) vulnerabilities.
function stripHtmlTags(htmlString) {
const htmlTagRegex = /<[^>]*>/g;
return htmlString.replace(htmlTagRegex, '');
}
// Example usage:
// console.log(stripHtmlTags("<h1>Hello <b>World</b>!</h1><script>alert('xss');</script>")); // "Hello World!"
// console.log(stripHtmlTags("Just plain text.")); // "Just plain text."
How it works: This `stripHtmlTags` function uses a regular expression `/<[^>]*>/g` to find and remove all HTML tags from a given string. It replaces any sequence starting with `<` and ending with `>` (with anything in between) with an empty string, effectively sanitizing the input against basic HTML injection and XSS attempts.