This question already has an answer here:
- Double quote in JavaScript string 4 answers
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("<img src=\"http://www.google.com\" />");
Now in the example above, you can see that I have begun the document.write
with double quotes "
and hence why I need to escape the quotes within the <img src="" />
to ensure that JavaScript still thinks that it's a string.
But in the below example you can see I have used a single quote '
to begin the document.write
statement. My question is do I need to still escape the double quotes? I know that the statement will work without this but what is best practice?
document.write('<img src=\"http://www.google.com\" />');
The reason I ask is I have a conditional statement that I've written that fires off an image (as per the line above) but it doesn't seem to be working and to rule out all possibilities as to what may be causing this. I come across stuff like this pretty much every day so any help would be much appreciated. This may perhaps be a daft question so apologies in advance...
When using single quotes you only need to escape single quotes, not double quotes.
(EDIT: And vice versa!)
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.
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
document.write('<img src="http://www.google.com" />');
Will work just fine.
same counts for document.write("<img src='http://www.google.com' />");
<html>
<body>
<script type="text/javascript">
document.write(escape("<img src=\"http://www.google.com\" />"));
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/10699726/escaping-characters-in-javascript-single-and-double-quotes