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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With