Javascript: Strings with single and double quotes

G

Gaspar

I really don't get when to use strings with single quotes, double
quotes, replace them by special html characters (&quot), etc.

Lots of problem arrise when my application outputs some html with a
string contaning single quotes, like "My name is Nick O'Haran", or even
some application-generated javascript code like "alert("This message
it's ok")". For example:

<input type="button" onclick="alert('My name is Nick O'Haran')">

or

<input type="button" onclick="someFunction();alert("This message it's ok")">

When do I have to replace single quotes by ' ?
When do I have to replace double quotes by &quot; ?
When do I have to backslash double quotes (" --> \") ?
Do Firefox and IE6 handle strings the same way?

Thanks in advanced.
 
T

Trevor Lawrence

Maybe a JS expert could give better info, but here goes (in-line)

Gaspar said:
I really don't get when to use strings with single quotes, double quotes,
replace them by special html characters (&quot), etc.

Lots of problem arrise when my application outputs some html with a string
contaning single quotes, like "My name is Nick O'Haran", or even some
application-generated javascript code like "alert("This message it's
ok")". For example:

<input type="button" onclick="alert('My name is Nick O'Haran')">

I would write
or

<input type="button" onclick="someFunction();alert("This message it's
ok")">

I would write
<input type="button" onclick="someFunction();alert('This message it\'s
ok')">
When do I have to replace single quotes by ' ?
You could use it in
<input type="button" onclick="someFunction();alert('This message it's
ok')">
When do I have to replace double quotes by &quot; ?
You could use it in
<input type="button" onclick="someFunction();alert(&quot;This message it's
ok&quot;)">
When do I have to backslash double quotes (" --> \") ?
When a double quote is open
Do Firefox and IE6 handle strings the same way?
Not sure

BTW, None of my suggestions are tested, although I have used similar.

The rule seems to be that if a double quote is open, quoting should be done
using single quotes and vice versa.
Or that you can use the HTML code for quote
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top