Skip to content

Instantly share code, notes, and snippets.

@asabaylus
Created July 2, 2015 14:49
Show Gist options
  • Save asabaylus/53378907a336cbbbce8b to your computer and use it in GitHub Desktop.
Save asabaylus/53378907a336cbbbce8b to your computer and use it in GitHub Desktop.
Scrub HTML from input
'use strict';
var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*',
tagOrComment = new RegExp(
'<(?:' +
// Comment body.
'!--(?:(?:-*[^->])*--+|-?)' +
// Special "raw text" elements whose content should be elided.
'|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' +
'|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*' +
// Regular name
'|/?[a-z]' +
tagBody +
')>', 'gi'
);
function decodeText(str) {
var txt = document.createElement('textarea');
txt.innerHTML = str;
return txt.value;
}
function sanitize(str) {
var oldStr;
do {
oldStr = str;
str = decodeText(str);
str = str.replace(tagOrComment, '');
} while (str !== oldStr);
return str.replace(/</g, '&lt;');
}
module.exports = sanitize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment