5

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 + "\"");
}
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. 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. Commented Jan 26, 2013 at 0:37
  • @Quentin Yes, I'd need to find a different solution. :/ 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)? Commented Jan 26, 2013 at 0:41

2 Answers 2

7

You can use JSON:

JSON.stringify(toPrint);
Sign up to request clarification or add additional context in comments.

6 Comments

I was about to post this as an answer, but you beat me to it. :)
Here's an example on jsfiddle (and it works as intended!) jsfiddle.net/jarble/x2mSt/1
I was just thinking about that, but it does not necessarily convert the string back to its literal form. E.g. "\n\nHi!\u000A" becomes "\n\nHi!\n".
@FelixKling - Good point. If you want the actual source code, you'd have to do an AJAX request for it.
Those are equivalent string literals. Information is lost when the source code is parsed, so you can't expect any better than that.
|
0
printStringLiteral("\\\n\\\nHi!");

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

2 Comments

The output of this function isn't correct - see here: jsfiddle.net/jarble/V6brF/2
This answer require the original string to escape it's `` chars, which is not what the OP asks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.