JAVASCRIPT

Remove HTML Tags from a String (Basic)

Perform basic HTML tag stripping from a string using a simple JavaScript regex. Useful for cleaning text, but not for robust security.

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

// Example:
const dirtyHtml = "<p>This is a <strong>bold</strong> paragraph with <a href='javascript:alert(1)'>a link</a>.</p>";
const cleanText = stripHtmlTags(dirtyHtml);
console.log(cleanText); // "This is a bold paragraph with a link."

// IMPORTANT: This is a basic stripper and should NOT be used for robust XSS prevention. 
// For security-critical applications, use a dedicated sanitization library like DOMPurify.
How it works: This JavaScript function removes HTML tags from a string using a straightforward regex. The pattern `/<[^>]*>/g` matches an opening angle bracket (`<`), followed by any character that is not a closing angle bracket (`[^>]`) zero or more times (`*`), and finally a closing angle bracket (`>`). The `g` flag ensures all occurrences are replaced. It's important to note this is a basic cleanup and is generally insufficient for preventing XSS vulnerabilities; for security, dedicated HTML sanitization libraries are recommended.

Need help integrating this into your project?

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

Hire DigitalCodeLabs