Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 46235  / 12 Years ago, tue, may 22, 2012, 12:00:00

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...


More From » escaping

 Answers
3

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



(EDIT: And vice versa!)


[#85428] Monday, May 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
addie

Total Points: 699
Total Questions: 89
Total Answers: 97

Location: Cayman Islands
Member since Fri, Mar 4, 2022
2 Years ago
;