Skip to content

Instantly share code, notes, and snippets.

@fernandosavio
Created August 4, 2017 22:04
Show Gist options
  • Select an option

  • Save fernandosavio/ff4285f772041d2fb102ff4bece62c20 to your computer and use it in GitHub Desktop.

Select an option

Save fernandosavio/ff4285f772041d2fb102ff4bece62c20 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"
@rad-z

rad-z commented Dec 13, 2018

Copy link
Copy Markdown

Thanks! This helped me tons.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment