Skip to content

Instantly share code, notes, and snippets.

@gregBerthelot
Forked from fernandosavio/striptags.js
Created April 14, 2020 11:52
Show Gist options
  • Save gregBerthelot/085c7fc48135ff6f9d16cc55f0b1f1bf to your computer and use it in GitHub Desktop.
Save gregBerthelot/085c7fc48135ff6f9d16cc55f0b1f1bf to your computer and use it in GitHub Desktop.
Simple regex-based strip_tags in Javascript
/*
regex example(strips 'i' and 'em' tags): /(<(?!\/?em|\/?i).*?>)/ig
*/
/**
* @param string html
* @param string allowed_tags space-separated allowed tags
*/
function strip_tags(html, allowed_tags){
allowed_tags = allowed_tags.trim()
if (allowed_tags) {
allowed_tags = allowed_tags.split(/\s+/).map(function(tag){ return "/?" + tag });
allowed_tags = "(?!" + allowed_tags.join("|") + ")";
}
return html.replace(new RegExp("(<" + allowed_tags + ".*?>)", "gi"), "");
}
var text = "<h1>Title</h1><p>Paragraph with <strong>bold</strong> and <em>italic</em> text. <a href='#'>A link</a></p>";
console.log(strip_tags(text, "p strong em"));
// "Title<p>Paragraph with <strong>bold</strong> and <em>italic</em> text. A link</p>"
console.log(strip_tags(text, "h1 p a"));
// "<h1>Title</h1><p>Paragraph with bold and italic text. <a href='#'>A link</a></p>"
console.log(strip_tags(text, "em"));
// "TitleParagraph with bold and <em>italic</em> text. A link"
console.log(strip_tags(text, ""));
// "TitleParagraph with bold and italic text. A link"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment