Skip to content Skip to sidebar Skip to footer

Escaping Characters In JavaScript Single And Double Quotes

I've got a question about escaping characters in JavaScript that I'm hoping you may be able to help with. Say if I have the following JavaScript code: document.write('

Solution 1:

When using single quotes you only need to escape single quotes, not double quotes.

(EDIT: And vice versa!)


Solution 2:

document.write('<img src="http://www.google.com" onClick="foo(\'bar\');" />'); 

You only need to escape the same kind of quotes that you are using.


Solution 3:

By now, you've got the picture: no need to escape quotes that you're not using as delimiters of that particular string. However: what is best practice is a different story. I know of some people who will tell you that 'always escaping quotes' is a good habit to get into. I disagree. Unlike some other languages JavaScript is reasonably lenient when it comes to escaped characters: in your second example, the backslashes won't be printed out.

This is not always the case, so My suggestion would be: be consistent in which quotes you use (single || double) and escape only the ones that need escaping. Depending on what other languages you're using, you might want to think a bit on which quotes you're going to use. If you're using PHP, for example, stick to single quotes, as double quotes do more than just delimiting a string. If you're used to writing C-like languages (or Java), best stay in the habit of using double quotes, since there is an even bigger difference between single and double quotes in those languages


Solution 4:

document.write('<img src="http://www.google.com" />'); Will work just fine.

same counts for document.write("<img src='http://www.google.com' />");


Solution 5:

<html>
<body>

<script type="text/javascript">

document.write(escape("<img src=\"http://www.google.com\" />"));

</script>

</body>
</html>

Post a Comment for "Escaping Characters In JavaScript Single And Double Quotes"