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
This question is related to
javascript
escaping
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";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
}
_x000D_
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.
JavaScript uses the \ (backslash) as an escape characters for:
Note that the \v and \0 escapes are not allowed in JSON strings.
You have to escape the backslash, so try this:
str = "Hello\\nWorld";
Here are more escaped characters in Javascript.
Source: Stackoverflow.com