简体   繁体   English

在 Javascript 中转义文字引号

[英]Escaping Literal Quotes in Javascript

How do I have two quoted phrases in javascript.我如何在 javascript 中有两个引用的短语。 This is the challenge: I am a double quoted string inside double quotes.这就是挑战:我是双引号内的双引号字符串。 I have this:我有这个:

" I am a \"double quoted\" string inside "double quotes\".";

many things possible:许多事情可能:

  • use character code 34 ( String.fromCharCode(34) ) and concatanate使用字符代码 34 ( String.fromCharCode(34) ) 并连接
  • double escape "\\\\\\""双转义"\\\\\\""
  • use single quotes to quote double quotes '"'使用单引号引用双引号'"'

probably more…可能更多…

 var q=String.fromCharCode(34); document.write(q+"quoted text, using a variable with String.fromCharCode(34)"+q+"<br>"); document.write("\\"quoted text, single escaped quotes\\"<br>"); document.write('"quoted text, quotes in single quotes"<br>'); document.write("you may use document.write(\\"\\\\\\"quoted text, single escaped quotes, displayed after double escaping\\\\\\"\\");<br>");

把它像这样:

    alert("I am a \"double quoted\" string inside \"double quotes\".");
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";

下面的代码在 chrome 浏览器上运行良好,但在 firefox 浏览器上出现错误。

var myStr = "I am a \"double quoted\" string inside \"double quotes\".";

it's a freecodecamp question.这是一个 freecodecamp 问题。 that's the solution to the problem;这就是问题的解决方案;

var myStr = "I am a \"double quoted\" string inside \"double quotes\".";

Just a note for anyone who may be confused with this example - while you need a \\ before the quoted text, both at the start and end of the quoted section, the \\ must always be in front of the quotation mark.任何人都只是说明谁可能与这个例子混淆-当你引用的文字之前,需要一个\\,无论是在开始和引用部分的最后,\\必须始终在引号的前面

var myStr = "I am a \"double quoted\" string inside \"double quotes\".";  //This is correct

var myStr = "I am a \"double quoted"\ string inside \"double quotes"\."; //This is incorrect

Even though logically you are still surrounding the quoted text with \\ marks, the second \\ marks are not in the right place.即使从逻辑上讲,您仍然用 \\ 标记包围引用的文本,但第二个 \\ 标记不在正确的位置。 The correct solution may look wrong visually to anyone used to normal written quotations but it is necessary for javascript to function.对于习惯于正常书面引用的任何人来说,正确的解决方案在视觉上可能看起来是错误的,但 JavaScript 的功能是必要的。 The period after "double quotes" is part of the general string and not part of the second quoted section. “双引号”之后的句点是一般字符串的一部分,而不是第二个引用部分的一部分。

var myStr="I am a \"double quoted\" string inside \"double quotes\"."; // Change this line

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM