JS Escape user input
Javascript Escape and htmlentities strings..
CSS
* { font:12px/10px 'courrier'; }
JavaScript
/*
Escape users input and htmlentities strings...
...Before working with them
molokoloco 2011 - www.b2bweb.fr
*/
// Escaping functions
var addslashes = function (str) {
return (str+'').replace(/\'/g,'\\\'').replace(/"/g, '"').replace(/\u0000/g, "\\0");
};
var input2html = function(str) {
return unescape((str+'')).replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
// Working String example
var inputString = "L'école \"te😂st\"<br />ok (&) !";
// Testing functions results
var echo = function(s) { document.write('<xmp>'+s+'</xmp>'); };
echo(addslashes(inputString )); // GOOD
echo(input2html(escape(inputString ))); // SAFE
// Compare with jQuery...
var decoded1 = $('<div/>').html(inputString ).text();
echo(decoded1);
var decoded2 = $('<div/>').text(inputString ).text();
echo(decoded2);