Escaping characters in single and double quotation marks JavaScript

I have a question about escaping characters in JavaScript where I hope you can help. 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 started document.writewith double quotes "and therefore why I need to escape the quotes in < img src="" />to make sure JavaScript still considers it to be a string.

But in the example below, you can see that I used a single quote 'to start the statement document.write. My question is do I still need to avoid double quotes? I know the expression will work without this, but what is the best?

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

The reason why I ask, I have a conditional statement that I wrote that works when I call (in accordance with the line above), but it does not seem to work and excludes all possibilities as to what might be causing this. I often see such things every day, so any help would be greatly appreciated. Maybe this might be a stupid question, so apologize in advance ...

+5
source share
5 answers

When using single quotes, you need to avoid single quotes, not double quotes.

(EDIT: And vice versa!)

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

You only need to avoid the same type of quotation marks that you use.

+3
source

: , . : - . , , " " - . . JavaScript , : .

, : , (single || double) , . , , , . , PHP, , . C- ( Java), , .

+3

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

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

+1
<html>
<body>

<script type="text/javascript">

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

</script>

</body>
</html>
0

All Articles