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
2 Answers
Reset to default 6You can use JSON:
JSON.stringify(toPrint);
printStringLiteral("\\\n\\\nHi!");
function printStringLiteral(toPrint){
console.log("\\\"" + toPrint + "\\\"");
}