JAVASCRIPT
Strip HTML Tags from a String using Regex
Learn to effectively remove all HTML tags from a string using a simple regular expression in JavaScript, useful for sanitizing user-generated content.
function stripHtmlTags(htmlString) {
const htmlTagRegex = /<[^>]*>/g;
return htmlString.replace(htmlTagRegex, '');
}
// Examples:
// const unsafeInput = "<p>This is a <b>test</b> with <script>alert('XSS');</script> tags.</p>";
// console.log(stripHtmlTags(unsafeInput)); // "This is a test with tags."
// console.log(stripHtmlTags("No tags here.")); // "No tags here."
How it works: The `stripHtmlTags` function uses a regular expression to remove all HTML tags from a given string. The regex `/<[^>]*>/g` matches any sequence starting with '<', followed by zero or more characters that are not '>', and ending with '>', effectively targeting and replacing all HTML tags with an empty string. This is a basic form of sanitization.