How to properly escape inline javascript


There are 3 ways to include javascript in your webpages.

1. as an external file
<script language='JavaScript' type='text/JavaScript' src='externalfile.js'></script>

2. in the body of your html file
<script language='JavaScript' type='text/JavaScript'>
alert('code for monkeys');
</script>

3. inline in html
<input type="button" value="push me" onclick="alert('code for monkeys');">

Question: How do you call alert when it has singled or double quotes in it?
Well in methods 1 and 2 you simply use ', or " example:
alert('john\'s code');
alert("john's \"code\"");

But what if you want to use inline javascript in html (method 3)? A quick googling of escape quotes in html yields an answer. Use &quot; for " (double quote) and &#39; for ' (single quote).
<input type="button" value="push" onclick="alert(&quot;john&#039;s code&quot;);" />
<input type="button" value="push" onclick="alert(&quot;john&#039;s \&quot;code\&quot;&quot;);" />

demo:







Now if we are using PHP to generate our html... it gets even worse trying to escape quotes for php, html and javascript and have everything work out correctly.

Use the json_encode() to sanitize the javascript, and htmlspecialchars() to sanitize the html attribute.

usage:
$js_string = "john's \"code\"";
$attribute = htmlspecialchars("alert(".json_encode($js_string).");");
echo '<input type="button" value="push" onclick="'.$attribute.'" />';
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)

meow on 2011-02-28 09:50:08
thanks, this helped me very much

Maruti Borker on 2011-04-08 13:56:28
I was trying to do similar stuff. But i was trying to pass a json from php to javascript in a inline html way. So. I didn't need to escape double quotes.

My code was :-

VAR_FOR_JS = ' ';

But if the json had it was not printing them as echo removes it . So firstly i replaced one slash with two slashes and also escaped a quote.

Rob on 2016-05-17 02:57:28
Thanks for that, you are awesome.