最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Print a JavaScript string as a string literal - Stack Overflow

programmeradmin5浏览0评论

I am attempting to print a string as a string literal in JavaScript, so that the string will be printed exactly as it is written:

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

I am attempting to print a string as a string literal in JavaScript, so that the string will be printed exactly as it is written:

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 + "\"");
}
Share Improve this question asked Jan 26, 2013 at 0:33 Anderson GreenAnderson Green 31.9k70 gold badges211 silver badges339 bronze badges 4
  • It's likely that I'd only need to put an escape character (`\`) before each character in the string - however, I haven't tested this solution yet. – Anderson Green Commented Jan 26, 2013 at 0:36
  • No, if you had the string "no" and did that then the first character would be turned into a new line escape sequence. – Quentin Commented Jan 26, 2013 at 0:37
  • @Quentin Yes, I'd need to find a different solution. :/ – Anderson Green Commented Jan 26, 2013 at 0:38
  • I don't think there is a way to convert a string back to its literal representation. A string is a sequence of Unicode code points, how would you know how the code was created (e.g. \n or \u000A)? – Felix Kling Commented Jan 26, 2013 at 0:41
Add a ment  | 

2 Answers 2

Reset to default 6

You can use JSON:

JSON.stringify(toPrint);
printStringLiteral("\\\n\\\nHi!");

function printStringLiteral(toPrint){
    console.log("\\\"" + toPrint + "\\\"");
}
发布评论

评论列表(0)

  1. 暂无评论