Skip to content

Instantly share code, notes, and snippets.

@timdp
Created December 2, 2014 17:44
Show Gist options
  • Save timdp/79c3eb57361c1df9b370 to your computer and use it in GitHub Desktop.
Save timdp/79c3eb57361c1df9b370 to your computer and use it in GitHub Desktop.
Simple self-contained HTTP sanitizer
var sanitize = (function() {
var re = /(.*?)<(\/?)\s*([A-Za-z]+)[^>]*>/mg;
var blockElements = ['br', 'div', 'p', 'blockquote'];
var inlineBlockElements = ['img'];
var sanitize = function(input) {
input = input.replace(/\s+/g, ' ');
var out = '';
var index = 0;
var match;
while (null !== (match = re.exec(input))) {
var before = match[1],
close = match[2],
tag = match[3].toLowerCase();
out += before;
if (!close) {
if (blockElements.indexOf(tag) >= 0) {
out += '\n';
} else if (inlineBlockElements.indexOf(tag) >= 0) {
out += ' ';
}
}
index = re.lastIndex;
}
out += input.substr(index);
return out;
};
return sanitize;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment