Friday, August 24, 2012

escape single quote javascript sanitize clean encode

found here after searching for the solution:
str = str.replace(/'/g, "\\'")

But I went ahead and improved the concept with a simple function:

function backslash(str){
var str = encodeURIComponent(str.replace(/'/g, "\\'"));
return str;

Named it backslash for simplicity but it actually will clean up # $ % ^ &() and anything else like single quote ' and doble quote (normally worked already)

Now you just plug this in where you need to clear up, i.e.:
var note = window.document.ordrfrm.note.value;

or simpler
var note = backslash(window.document.ordrfrm.note.value);

Which ever will work even with getElementById and now it's easy to play with the note, user input taken like a champ nothing is screwed up when encounters strange characters (strange for javascript at least)!

hope it helps someone, if you like it or have questions post a comment.

thanks for visiting Edu Boris blog.

1 comment:

Nigel said...

Thanks Boris, tried several solutions for single quotes in the text, but yours is the only one that worked.