Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to show escape characters in a string? [duplicate]

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 
like image 534
Jazcash Avatar asked Feb 10 '14 08:02

Jazcash


People also ask

How do you find duplicate characters in a given string JavaScript?

you can use . indexOf() and . lastIndexOf() to determine if an index is repeated. Meaning, if the first occurrence of the character is also the last occurrence, then you know it doesn't repeat.

How do you escape special characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.

What is escape () in JS?

Definition and Usage The escape() function was deprecated in JavaScript version 1.5. Use encodeURI() or encodeURIComponent() instead. The escape() function encodes a string. This function makes a string portable, so it can be transmitted across any network to any computer that supports ASCII characters.


1 Answers

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.

like image 91
T.J. Crowder Avatar answered Oct 04 '22 06:10

T.J. Crowder