2

我试图在 JavaScript 中将字符串打印为字符串文字,以便字符串将完全按照其编写方式打印:

printStringLiteral("\n\nHi!");//this prints "Hi!" instead of "\n\nHi!".
                              //What will I need to do in order to print
                              //the string as a string literal instead?

function printStringLiteral(toPrint){
    console.log("\"" toPrint + "\"");
}
4

2 回答 2

4

您可以使用 JSON:

JSON.stringify(toPrint);
于 2013-01-26T00:44:59.200 回答
0
printStringLiteral("\\\n\\\nHi!");

function printStringLiteral(toPrint){
    console.log("\\\"" + toPrint + "\\\"");
}
于 2013-01-26T00:37:50.433 回答