简体   繁体   中英

Escaping Literal Quotes in Javascript

How do I have two quoted phrases in 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
  • 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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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