将 JavaScript 字符串打印为字符串文字

And*_*een 3 javascript

我正在尝试在 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 + "\"");
}
Run Code Online (Sandbox Code Playgroud)

gil*_*ly3 5

您可以使用 JSON:

JSON.stringify(toPrint);
Run Code Online (Sandbox Code Playgroud)