How should I escape a string that will be going into a Javascript String? URLEncode(X)? str_replace(\"\'\",\"\\\'\",X)?
There a couple of things you should do to escape your input. At a minimum do #1:
The addslashes function will add backslashes before single ('
) and double ("
) quotes, backslashes (\
), and NUL (\0
).
For extra safety wrap your entire script section in CDATA tags so you can validate the script as XHTML even if it contains <
or >
:
Also if you're really paranoid you'll break up any occurrences of and
]]>
since those can interfere with the HTML parser. For example, replace with
<"+"/script>
and ]]>
with ]]"+">
. Again that depends on how anal you are about protecting yourself from malicious/questionable user input.