Single quote escape in JavaScript function parameters

 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.

Leave a Comment