Javascript sanitizer
by pddring
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<h2>The challenge:</h2><p> To allow images and links but not to allow any scripts or embedded content
</p>
<h3>Input html:</h3>
<textarea id="input">Test the input filter here</textarea>
<button id="btnGo">Sanitize</button>
<h3>Sanitized output:</h3>
<div id="output">
Press go to test
</div>
CSS
#output {
border: 1px solid #000;
}
JavaScript
function sanitize(input) {
function replace(match) {
// allow attributes for images and links except for event handlers
if(match.match(/^\s*(href|src)/i)) {
return match.replace(/on[a-z]+\s*=\s*(("[^"]*")|('[^']*'))/i, "");
}
return "";
}
var white="b|i|p|br|a|img";//allowed tags
var black="script|object|embed";//complete remove tags
var e=new RegExp("(<("+black+")[^>]*>.*</\\2>|(?!<[/]?("+white+")(\\s[^<]*>|[/]>|>))<[^<>]*>|(?!<[^<>\\s]+)\\s[^</>]+(?=[/>]))", "gi");
output = input.replace(e,replace);
return output;
}
$('#btnGo').click(function() {
var input = $('#input').val();
var output = sanitize(input);
$('#output').text(output);
});