JavaScript字符串中的双引号

40

我如何在JavaScript字符串中包含双引号以在浏览器中显示?

我正在做我的JavaScript作业,我必须在我的列表中间包含双引号,如下所示:

if (i == 0) {

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

72

使用单引号。

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

或者转义双引号。

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

8

使用单引号作为字符串的定界符:

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

如果字符串中有单引号,请用双引号括起来。

如果字符串中有双引号,请用单引号括起来。

如果需要在字符串中使用两种引号,请在所选定的分隔符前加上\进行转义。


5
考虑使用默认的实体。
 &quot;

这样做不行,因为作者询问的是 JavaScript 字符串中的文本区域。即使它是 JavaScript 中的 HTML 区域,你也不需要实体。只有在实际的 HTML 中才需要。 - Jeanne Boyarsky
1
该字符串显然旨在生成一些HTML片段。在此情况下,它肯定有效(已通过jsfiddle检查)。选择使用提议的选项是提问者的选择。 - stefan bachert

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

或者,如果你使用的是单引号是惯用法的英语变体,就像英式英语一样,

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

使用适当的标点符号,您将不会遇到JavaScript引用约定的问题。计算机语言使用ASCII引号,而人类语言则不使用。

只需确保您的文档已正确编码(这里可以使用Windows-1252UTF-8),并且已正确声明编码方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接