81

Very simple question, but for some reason I can't find the answer anywhere after 10 minutes of Googling. How can I show escape characters when printing in Javascript?

Example:

str = "Hello\nWorld";
console.log(str);

Gives:

Hello
World

When I want it to give:

Hello\nWorld
Jazcash
  • 3,145
  • 2
  • 31
  • 46
  • 6
    This question is marked as a duplicate, but I think the answer that everyone expects is here. :) – Jonathan H Sep 07 '17 at 18:32
  • 2
    I'd like to add the answer that one can simply use `String.raw\`Hello\nWorld\`` but this question has been incorrectly marked as duplicate – Somo S. Aug 26 '18 at 15:42

3 Answers3

132

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

const str = "Hello\nWorld";
const json = JSON.stringify(str);
console.log(json); // ""Hello\nWorld""
for (let i = 0; i < json.length; ++i) {
    console.log(`${i}: ${json.charAt(i)} (0x${json.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")})`);
}
.as-console-wrapper {
    max-height: 100% !important;
}

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This did the job, thanks! The reason I accepted this answer is because it works with non-literal strings and doesn't involve modifying the string itself. – Jazcash Feb 10 '14 at 08:45
  • but if we don't use an existing special character (combined with the backslash) js will trim it out before the stringify `console.log(JSON.stringify("asdasd\Sasdasd")); // "asdasdSasdasd"` `console.log("asdasd\Sasdasd"); // asdasdSasdasd` – icosamuel May 28 '18 at 14:38
  • 1
    @icosamuel - There is no backslash in that string. `"asdasd\Sasdasd"` is `"asdasdSasdasd"`. When you escape a character that doesn't have special meaning, the result is just the character. Put it another way, `"\S".length` is 1, because that defines a one-character string with an S in it, exactly like `"S"` does. – T.J. Crowder May 28 '18 at 14:52
  • interesting! Is there any way to treat them as cleartext outside of escaping the original backslash? `\\S` – icosamuel May 28 '18 at 15:36
  • 1
    @icosamuel - Not with a string literal; as soon as the string literal is parsed, that ``\`` is gone because it has no meaning. If you use a template literal, you can use the `String.raw` tagged template function: `String.raw\`\S\`` (notice that those are backticks, not quotes) returns `"\\S"`. – T.J. Crowder May 28 '18 at 16:21
  • 1
    I hadn't thought of using JSON.stringify on anything other than objects, this is super-helpful. Thanks! – Josh Powlison Nov 26 '18 at 15:56
  • 1
    @BobStein - Done! – T.J. Crowder Jul 17 '19 at 15:02
  • Could not detect ASCII 160. Someone else might be scratching their head with this. It is a space character that originates form HTML nbsp. You can use charCodeAt() function to verify the same. – Sanjay Vamja Jan 27 '22 at 18:23
  • 1
    @SanjayVamja - Yes, that's [U+00A0](https://util.unicode.org/UnicodeJsps/character.jsp?a=00A0), the primary non-breaking space. The escape for it in a JavaScript string literal is `\xA0` or `\u00A0`, but it's perfectly valid as a literal character. – T.J. Crowder Jan 27 '22 at 19:23
28

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

PoppinL
  • 446
  • 3
  • 7
22

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

philshem
  • 24,761
  • 8
  • 61
  • 127