JAVASCRIPT

Removing HTML Tags from a String (Basic Sanitization)

Learn to strip HTML tags from user-provided strings using a simple regular expression in JavaScript, useful for basic content cleaning.

function stripHtmlTags(htmlString) {
  const htmlTagRegex = /<[^>]*>/g;
  return htmlString.replace(htmlTagRegex, '');
}

// Examples:
// const unsafeInput = "<p>Hello, <b>world</b>!</p><script>alert('xss');</script>";
// console.log(stripHtmlTags(unsafeInput)); // "Hello, world!" (Note: Basic, not a security solution for all XSS)
// console.log(stripHtmlTags("No tags here.")); // "No tags here."
How it works: This function uses a regular expression to find and replace all HTML tags within a given string with an empty string. The regex `/<[^>]*>/g` matches any sequence starting with `<` and ending with `>`, effectively removing basic HTML elements. Note that this is a basic cleanup and not a full XSS prevention solution; for robust security, use dedicated sanitization libraries.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs