JAVASCRIPT

Remove HTML Tags from a String

Sanitize or convert rich text to plain text by removing all HTML tags from a string using a concise JavaScript regular expression.

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

// Usage:
// const richText = "<h1>Title</h1><p>Some <strong>bold</strong> text.</p>";
// console.log(stripHtmlTags(richText)); // "TitleSome bold text."

// const simpleText = "No HTML here.";
// console.log(stripHtmlTags(simpleText)); // "No HTML here."
How it works: This JavaScript function removes all HTML tags from a string, effectively converting rich text to plain text. It uses the regular expression `/<[^>]*>/g` to find any sequence starting with `<` and ending with `>`, matching any characters in between, and then replaces all occurrences with an empty string. This is useful for sanitization or display purposes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs