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

时间:2013-01-26 00:33:22

标签: 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 + "\"");
}

2 个答案:

答案 0 :(得分:3)

您可以使用JSON:

JSON.stringify(toPrint);

答案 1 :(得分:0)

printStringLiteral("\\\n\\\nHi!");

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