Escaping Characters in Javascript

The characters "(quotation mark), '(single quote) and /(forward slash) are integral to the javascript code itself. So depending on how your javascript is constructed, at least two of these characters must be escaped when used in a javascript. To do that, a \ (backward slash) is placed before each of the aforementioned characters. Without these backward slashes, there is a very high likelihood that your script will not appear at all.

If you wish to display " (quotation marks) in the displayed text area of your javascript, precede the character with \ (backward slash). Or you can also use the character entity rather than the character itself. For instance, if you want to display the sentence

Murphy's Law states, "Everything that can go wrong will go wrong."

You would type the following inside your script tags:

document.write("<p>Murphy's Law states, <i>\"Everything that can go wrong will go wrong.\"<\/i><\/p>");

or

document.write("<p>Murphy's Law states, <i>&quot;Everything that can go wrong will go wrong.&quot;<\/i><\/p>");

Another way to get around this problem is to always use single quote marks to surround the javascript text area. However, in that case, then all instances of ' (single quote) would have to be escaped. They can either be preceded by the \ (backward slash) or replaced with &#039;. And the / (forward slash) will still have to be escaped:

document.write('<p>Murphy\'s Law states: <i>"Everything that can go wrong will go wrong."<\/i><\/p>');

or

document.write('<p>Murphy&#039;s Law states: "Everything that can go wrong will go wrong."<\/p>');

if your javascript is inside an HTML link:

<a href="murphyslaw.html" title="&quot;Murphy's Law&quot;"
onclick="var w=window.open('murphyslaw.html', 'popup', 'scrollbars=1,resizable=1,width=590,height=400,left=20,top=20');
return false;"
onmouseover="setAttribute('title', '&quot;Murphy\'s Law&quot; opens in a popup')">Murphy's Law</a>

No matter how you look at it, unless you avoid the use of the characters ', " and / completely, some escaping of characters may be required in the displayed text areas of your javascripts.

return to tutorial and/or