40

How can I include a double quote in a JavaScript string to be shown in the browser?

I am working on my JavaScript homework and I have to include double quotes in the middle of my list as shown below:

if (i == 0) {

   error +=  "<li> this is not the name "....." </li>\n"
}

4 Answers 4

73

Use single quotes.

error += '<li> this is not the name "....." </li>\n';

Or escape the double quotes.

error += "<li> this is not the name \".....\" </li>\n";
Sign up to request clarification or add additional context in comments.

Comments

9

Use single quotes as your string delimiters:

if (i == 0) {
   error += '<li> this is not the name "....." </li>\n'
}

If you have single quotes in the string, delimit it with double quotes.

If you have double quotes in the string, delimit it with single quotes.

If you need to use both types in the string, escape whatever delimiter you have chosen by prefixing it with a \.

Comments

7

Consider to use the default entity

 &quot;

2 Comments

That won't work because the author is asking about a text region in a JavaScript string. Even it was an HTML region in a JavaScript you wouldn't need entities. Only for actual HTML
The string is obviously intended to generate some html fragment. And in this context it WORKS definitely (checked with jsfiddle). It is the askers choice to decide between the proposed options
1
error +=  "<li> this is not the name “.....” </li>\n"

Or, if you use a variant of English where single quotation marks are the norm, as usual in British English,

error +=  "<li> this is not the name ‘.....’ </li>\n"

Using proper punctuation marks, you won’t encounter problems with the quoting conventions of JavaScript. Computer languages use ASCII quotes, human languages don’t.

Just make sure your document is properly encoded (both Windows-1252 and UTF-8 would do here) and the encoding is properly declared.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.