Duplicated Duplicated - 4 months ago 8x
jQuery Question

Javascript XSS Validation

I have a javascript / jquery code for searching and i tested inserting a script tag with an alert and i found out that my search was vulnerable to an XSS. May i ask if is there a way to filter the search?

Here is my code.

if($.trim($(this).val()) != ''){
$.get("php/api.php",{"function":"Searching","search": $(this).val() },function(e){
if(e.which == 13) {
location.href = 'search.php?result='+$(this).val();


To remove the script tag from user input you can use the below function

 function stripScripts(s) {
    var div = document.createElement('div');
    div.innerHTML = s;
    var scripts = div.getElementsByTagName('script');
    var i = scripts.length;
    while (i--) {
    return div.innerHTML;

 stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script><\/span>')

But thats going to prevent only a specfic type of XSS. Check this link for more details.