Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  24] [ 3]  / answers: 1 / hits: 163787  / 11 Years ago, mon, february 10, 2014, 12:00:00

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 = HellonWorld;
console.log(str);


Gives:



Hello
World


When I want it to give:



HellonWorld

More From » escaping

 Answers
13

If your goal is to have


str = "HellonWorld";

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


console.log(JSON.stringify(str)); // ""HellonWorld""



const str = HellonWorld;
const json = JSON.stringify(str);
console.log(json); // HellonWorld
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.


[#72620] Saturday, February 8, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carlton

Total Points: 373
Total Questions: 123
Total Answers: 97

Location: Saint Helena
Member since Wed, Nov 9, 2022
2 Years ago
carlton questions
Sun, Apr 25, 21, 00:00, 3 Years ago
Wed, Feb 17, 21, 00:00, 3 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Mon, Apr 13, 20, 00:00, 4 Years ago
;