If your goal is to create a string using a string literal like this:

str = "Hello\nWorld";

and output what it contains in string literal form (a fairly specific use case), 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(`{json.charAt(i)} (0x${json.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")})`);
}
.as-console-wrapper {
    max-height: 100% !important;
}

This is a fairly unusual thing to want to do, though helpful sometimes for debugging in awkward situations where, for whatever reason, you can't use a debugger directly.

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.


To be clear, if you just want to create a string with H, e, l, l, o, \, n, W, o, r, l, d in it, you don't need JSON.stringify for that. Just escape the backslash so it's not treated as an escape character: "Hello\\nWorld"

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

The JSON.stringify thing is just for situations where you want to see a string-literal-like output for a string with things like newlines in it, usually for debugging.

Answer from T.J. Crowder on Stack Overflow
🌐
SSOJet
ssojet.com › escaping › javascript-string-escaping-in-javascript-in-browser
JavaScript String Escaping in JavaScript in Browser | Escaping Techniques in Programming
For instance, hexadecimal and Unicode escapes are commonly used. A hexadecimal escape sequence, like \x41, will render as the character "A".
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Regular_expressions › Character_escape
Character escape: \n, \u{...} - JavaScript | MDN
1 week ago - In Unicode-unaware mode, escape sequences within character classes of the form \cX where X is a number or _ are decoded in the same way as those with ASCII letters: \c0 is the same as \cP when taken modulo 32. In addition, if the form \cX is encountered anywhere where X is not one of the recognized characters, then the backslash is treated as a literal character.
People also ask

What Are Escape Characters?
Escape characters are special sequences used in strings to achieve specific formatting or include characters that are otherwise reserved or difficult to type. By starting with a backslash (\), these sequences signal JavaScript to interpret the next character differently. In simple terms, escape characters "break the rules" of normal string syntax. For instance, using a single quote inside a string surrounded by single quotes normally causes an error. However, using an escape character like \' resolves this issue. They are essential for clean, error-free code when dealing with complex strings.
🌐
d-libro.com
d-libro.com › javascript coding with ai › escape characters
Mastering Escape Characters in JavaScript: A Complete Guide - Topic
How Can Escape Characters Be Combined in Strings?
Escape characters can be used together to create complex strings that apply universally, regardless of the operating system. For example, combining line breaks (\n), tabs (\t), and quotes (\") can help create a formatted shopping list or other structured text outputs.
🌐
d-libro.com
d-libro.com › javascript coding with ai › escape characters
Mastering Escape Characters in JavaScript: A Complete Guide - Topic
What Are Commonly Used Escape Characters?
Escape characters in JavaScript serve specific purposes, such as formatting strings, embedding special characters, and creating readable code. Commonly used escape characters include: New Line (\n) and Tab (\t): \n adds a new line, splitting text into multiple lines, while \t inserts a tab space, useful for alignment and structured output. Backslash (\\) and Quotes (\', \"): \\ represents a literal backslash, crucial for file paths or escaping other characters. \' and \" allow single or double quotes to be included within strings without causing syntax errors. Special Characters (\u U
🌐
d-libro.com
d-libro.com › javascript coding with ai › escape characters
Mastering Escape Characters in JavaScript: A Complete Guide - Topic
🌐
D-libro
d-libro.com › javascript coding with ai › escape characters
Mastering Escape Characters in JavaScript: A Complete Guide - Topic
January 13, 2025 - Let’s explore the commonly used escape characters alongside practical examples of their usage. \n: Adds a new line, splitting text into multiple lines. \t: Inserts a tab space, useful for alignment and structured output. ... let message = "Hello there!\nWelcome to JavaScript."; console.log(message); // Output: // Hello there!
🌐
W3Schools
w3schools.com › js › js_strings.asp
JavaScript Strings
1 month ago - Templates are strings enclosed ... be chopped to "We are the so-called ". To solve this problem, you can use an backslash escape character....
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript - Escape Sequences in Strings - JavaScript - The freeCodeCamp Forum
April 28, 2023 - Tell us what’s happening: KEEPS GIVING ME AN ERROR I cannot move forward with the lesson, went to the video “Help” and as well this frum and latest update is August 2019. Changed even the var to const and still same issues, no variation of solution works Your code so far var myStr=‘FirstLine\n\t\\\SecondLine\\n\ThirdLine’; // Change this line const myStr=‘FirstLine\n\t\\\SecondLine\\n\ThirdLine’; // Change this line var myStr=\t‘FirstLine\n\SecondLine\\rThirdLine’; // Change this line Your...
Top answer
1 of 3
147

If your goal is to create a string using a string literal like this:

str = "Hello\nWorld";

and output what it contains in string literal form (a fairly specific use case), 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(`{json.charAt(i)} (0x${json.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")})`);
}
.as-console-wrapper {
    max-height: 100% !important;
}

This is a fairly unusual thing to want to do, though helpful sometimes for debugging in awkward situations where, for whatever reason, you can't use a debugger directly.

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.


To be clear, if you just want to create a string with H, e, l, l, o, \, n, W, o, r, l, d in it, you don't need JSON.stringify for that. Just escape the backslash so it's not treated as an escape character: "Hello\\nWorld"

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

The JSON.stringify thing is just for situations where you want to see a string-literal-like output for a string with things like newlines in it, usually for debugging.

2 of 3
30

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.

🌐
John Kavanagh
johnkavanagh.co.uk › home › articles › escaping and unescaping special characters in js
Escaping and Unescaping Special Characters in JavaScript
February 6, 2025 - This is really important when dealing ... Let's talk through some common scenarios. In JavaScript, you can escape characters using a backslash (\)....
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Escape Sequence Javascript - JavaScript - The freeCodeCamp Forum
February 23, 2017 - Tried many ways, and looked for many examples. For the returns, how should they be written? I couldn’t find examples to save my life, and when tried on my own the closest I came was 3 out of 4… var myStr= "FirstLine\n\\SecondLine\\r\ThirdLine";
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › what-are-escape-characters-in-javascript
What are Escape Characters in JavaScript ? - GeeksforGeeks
May 7, 2023 - Escape characters are characters that are used when working with special characters like single quotes, and double quotes, To print these characters as it is, including the backslash ‘\’ in front of them.
🌐
Fridoverweij
library.fridoverweij.com › docs › jstutorial › unicode_and_escape_sequences.html
JavaScript Tutorial – Unicode and escape sequences
May 7, 2025 - Escape sequence: \r\n. A "next ... are defined as listed above, various programming languages treat them in various ways. JavaScript treats \n (or \u{000A}) as a newline instead of a line feed....
🌐
MojoAuth
mojoauth.com › escaping › javascript-string-escaping-in-nodejs
JavaScript String Escaping in NodeJS | Escaping Methods in Programming Languages
In JavaScript, certain characters are reserved for specific functions, such as quotes and backslashes. To include these characters in a string, you need to escape them using a backslash (``). Here are some commonly used escape sequences in ...
🌐
Quora
quora.com › What-are-the-escape-characters-in-JavaScript
What are the escape characters in JavaScript? - Quora
Answer (1 of 2): What are the escape characters in JavaScript? [code]\ [/code]What are escape characters in computer programming? Escape characters are used to remove the special meaning that some characters have in a scripting/programming language, or to indicate a special meaning for other ch...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › escape
escape() - JavaScript | MDN
The escape() function replaces all characters with escape sequences, with the exception of ASCII word characters (A–Z, a–z, 0–9, _) and @\*_+-./. Characters are escaped by UTF-16 code units. If the code unit's value is less than 256, it is represented by a two-digit hexadecimal number ...
🌐
React
react.dev › learn › escape-hatches
Escape Hatches – React
For example, you might need to focus an input using the browser API, play and pause a video player implemented without React, or connect and listen to messages from a remote server. In this chapter, you’ll learn the escape hatches that let you “step outside” React and connect to external systems.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-escape-strings-in-javascript
How to Escape a String in JavaScript – JS Escaping Example
November 7, 2024 - In JavaScript, you can use the opposite string syntax ' or " to escape a string.
🌐
BitDegree
bitdegree.org › learn › best-code-editor › javascript-string-example-5
Escape Characters in a JavaScript String: an Example to Follow
This JavaScript string example illustrates how to use escape characters inside a JS string to avoid problems. Learn how to include single escape quotes.
🌐
CodeSignal
codesignal.com › learn › courses › string-manipulation-for-js-beginners › lessons › unleashing-javascript-a-deep-dive-into-escape-characters-and-special-characters
A Deep Dive into Escape Characters and Special Characters
In this instance, the escape character (\) inserts double quotes into the string. Without it, the JavaScript compiler would throw an error. Other frequently used escape sequences include \t (tab), \n (new line), and \\ (backslash).