Single quote escape in JavaScript function parameters

Daniele Di Punzio picture Daniele Di Punzio · Jan 5, 2012 · Viewed 83.5k times · Source

I need to escape single quotes in JavaScript function parameters to avoid this:

onclick="Javascript:INSERT_PRODUCT('188267','WILL AND GRACE','32311','L'ANNIVERSARIO DINOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5  ',this);"

But I need to escape them inside a function call since I do not know the values that will be passed (db variables I can't escape from the database).

Is there a function that allows me to do something like the following?

onclick="Javascript:function(escape(param1), escape(param2), escape(param3));"

Answer

Mike Samuel picture Mike Samuel · Jan 5, 2012
 JSON.stringify(plainTextStr).replace(/&/, "&").replace(/"/g, """)

will produce a string you can safely embed in a quoted attribute and which will have the same meaning when seen by the JavaScript interpreter.

The only caveat is that some Unicode newlines (U+2028 and U+2029) need to be escaped before being embedded in JavaScript string literals, but JSON only requires that \r and \n be escaped.