Javascript XSS Prevention

Here is a general encode procedure:

var lt = /</g, 
    gt = />/g, 
    ap = /'/g, 
    ic = /"/g;
value = value.toString().replace(lt, "&lt;").replace(gt, "&gt;").replace(ap, "&#39;").replace(ic, "&#34;");

If your user doesn't submit anything to your server you don't even need the above. If the user submits and you are using the user input then the above should be safe. As long as the '<' and '>' are globally sanitized and the parenthesis also are you are good to go.


Considering https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

Here is an implementation of their recommendations :

function escapeOutput(toOutput){
    return toOutput.replace(/\&/g, '&amp;')
        .replace(/\</g, '&lt;')
        .replace(/\>/g, '&gt;')
        .replace(/\"/g, '&quot;')
        .replace(/\'/g, '&#x27;')
        .replace(/\//g, '&#x2F;');
}

Also make sure you use this function only when necessary or you might break some stuff.

But I suggest you to take a look at already made libraries for sanatizing output :

https://github.com/ecto/bleach


why not use encodeURIComponent before sending the data to the client?

var string="<script>...</script>";
string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3