Skip to content

Instantly share code, notes, and snippets.

@mrtrom
Created March 16, 2017 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtrom/17d42c52c90530e232fe9da036d772ca to your computer and use it in GitHub Desktop.
Save mrtrom/17d42c52c90530e232fe9da036d772ca to your computer and use it in GitHub Desktop.
Removes HTML tags from a string that are not listed in the whitelist
/*
<b> - bold, use as last resort <h1>-<h3>, <em>, and <strong> are
preferred.
<blockquote> - specifies a section that is quoted from another source.
<code> - defines a piece of computer code.
<del> - delete, used to indicate modifications.
<dd> - describes the item in a <dl> description list.
<dl> - description list.
<dt> - title of an item in a <dl> description list.
<em> - emphasized.
<h1>, <h2>, <h3> - headings.
<i> - italic.
<img> - specifies an image tag.
<kbd> - represents user input (usually keyboard input).
<li> - list item in an ordered list <ol> or an unordered list <ul>.
<ol> - ordered list.
<p> - paragraph.
<pre> - pre-element displayed in a fixed width font and and
unchanged line breaks.
<s> - strikethrough.
<sup> - superscript text appears 1/2 character above the baseline
used for footnotes and other formatting.
<sub> - subscript appears 1/2 character below the baseline.
<strong> - defines important text.
<strike> - strikethrough is deprecated, use <del> instead.
<ul> - unordered list.
<br> - line break.
<hr> - defines a thematic change in the content, usually via a
horizontal line.
*/
function cleanEvilTags(string) {
if (!string) return '';
var whitelistTags = 'b|blockquote|code|del|d[d|l|t]|em|h[1-7]|i|kbd|[o|i|u]l|p|pre|s|sup|sub|strong|strike|br|hr';
var regex = new RegExp('\<(?!\/?(' + whitelistTags + ')[ >])[^>]*\>', 'ig');
return string.replace(regex, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment