我正在尝试在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 + "\"");
}
答案 0 :(得分:3)
您可以使用JSON:
JSON.stringify(toPrint);
答案 1 :(得分:0)
printStringLiteral("\\\n\\\nHi!");
function printStringLiteral(toPrint){
console.log("\\\"" + toPrint + "\\\"");
}