JAVASCRIPT
Strip HTML Tags from a String for Plain Text
Efficiently remove all HTML tags from a given string in JavaScript using a simple regular expression to obtain clean, plain text content.
const stripHtmlTags = (htmlString) => {
return htmlString.replace(/<[^>]*>/g, '');
};
const htmlContent = "<h1>Title</h1><p>This is a <strong>paragraph</strong> with <em>emphasis</em>.</p>";
console.log(stripHtmlTags(htmlContent)); // "TitleThis is a paragraph with emphasis."
const messyHtml = "<div><p>Hello</p> <br> <span>World!</span></div>";
console.log(stripHtmlTags(messyHtml)); // "Hello World!"
How it works: This snippet provides a straightforward way to remove all HTML tags from a string. The regular expression `<[^>]*>` matches any sequence starting with `<` and ending with `>`, effectively capturing entire HTML tags. The `replace()` method then substitutes these matched tags with an empty string, leaving only the plain text content.