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
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › escape
escape() - JavaScript - MDN Web Docs - Mozilla
It is not required to be implemented by all JavaScript engines and may not work everywhere. Use encodeURIComponent() or encodeURI() if possible. The escape() function computes a new string in which certain characters have been replaced by hexadecimal escape sequences.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Regular_expressions › Character_escape
Character escape: \n, \u{...} - JavaScript - MDN Web Docs
5 days ago - For example, \cJ represents line break (\n), because the code point of J is 74, and 74 modulo 32 is 10, which is the code point of line break. Because an uppercase letter and its lowercase form differ by 32, \cJ and \cj are equivalent. You can represent control characters from 1 to 26 in this form.
People also ask

What Are Tips for Using Template Literals Instead of Escape Characters?
Template literals, enclosed by backticks (`), often eliminate the need for escape characters. They allow for multi-line strings and embedded expressions, making code more readable and maintainable. Template literals will be explained in more detail later in this chapter.
🌐
d-libro.com
d-libro.com › javascript coding with ai › escape characters
Mastering Escape Characters in JavaScript: A Complete Guide - Topic
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
🌐
Mathias Byens
mathiasbynens.be › notes › javascript-escapes
JavaScript character escape sequences · Mathias Bynens
December 21, 2011 - The caret notation character following \c in this kind of character escape is case-insensitive; in other words, /\cJ/ and /\cj/ are equivalent. Here’s a list of all the available control escape sequences and the control characters they map to: You could define control escape syntax using the following regular expression: \\c[a-zA-Z]. I wrote a JavaScript string escaper that combines these different kinds of escapes (except the deprecated octal escapes) and returns the smallest possible result string.
🌐
Rip Tutorial
riptutorial.com › escape sequence types
JavaScript Tutorial => Escape sequence types
For example, in alert("Hello\nWorld");, the escape sequence \n is used to introduce a newline in the string parameter, so that the words "Hello" and "World" are displayed in consecutive lines.
🌐
CodeBasics
code-basics.com › programming › javascript course › escape sequences
Escape sequences | JavaScript | CodeBasics
If we need to print \n as a text (two separate characters), we can use the escape character, adding another \ at the beginning. I.e., the sequence of \n will be printed as characters \ and n following each other · console.log('Joffrey loves using \\n');Expand code ... A small but important note about Windows. Windows uses \r\n by default to enter a line break. This combination works well on Windows but creates problems when copied to other systems (for example, when the development team includes both Windows and Linux users).
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.

Find elsewhere
🌐
D-libro
d-libro.com › javascript coding with ai › escape characters
Mastering Escape Characters in JavaScript: A Complete Guide - Topic
January 13, 2025 - Chapter 11. Building Web Applications in JavaScript ... 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.
🌐
Quackit
quackit.com › javascript › tutorial › javascript_escape_characters.cfm
JavaScript Escape Characters
In JavaScript, the backslash (\) is an escape character. As an example, let's say I want to display the following text: They call it an "escape" character.
🌐
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).
🌐
freeCodeCamp
freecodecamp.org › news › how-to-escape-strings-in-javascript
How to Escape a String in JavaScript – JS Escaping Example
November 7, 2024 - Template Literals are string literals that allow you to embed expressions inside a string, using the syntax ${expression}. let quote = `He said, "I learned from freeCodeCamp!"`; console.log(quote); // He said, "I learned from freeCodeCamp!"
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › RegExp › escape
RegExp.escape() - JavaScript - MDN Web Docs
July 10, 2025 - For example, RegExp.escape("foo") returns "\\x66oo" (here and after, the two backslashes in a string literal denote a single backslash character). This step ensures that if this escaped string is embedded into a bigger pattern where it's immediately preceded by \1, \x0, \u000, etc., the leading ...
🌐
TutorialsPoint
tutorialspoint.com › escape-characters-in-javascript
Escape characters in JavaScript
June 16, 2023 - Escape characters are characters that can be interpreted in some alternate way then what we intended to. To print these characters as it is, include backslash ‘\’ in front of them. Following are the escape characters in JavaScript &min
🌐
JavaScript in Plain English
javascript.plainenglish.io › chapter-23-mastering-escape-sequences-in-javascript-a-beginners-guide-to-special-characters-7b17c40e1b9a
Chapter 23:Mastering Escape Sequences in JavaScript: A Beginner’s Guide to Special Characters | by Aryan kumar | JavaScript in Plain English
October 15, 2024 - Escape sequences are handy, but they can also lead to bugs if used incorrectly. Let’s take a look at a few common mistakes. let message = "Hello "World"!"; // ⚠️ Error: Unexpected string · In this example, JavaScript thinks the second double quote ends the string, causing an error.
🌐
Codedamn
codedamn.com › news › javascript
How to Escape a String in JavaScript – Complete Guide
June 7, 2023 - A: To escape a newline character in a regular JavaScript string, use the \n escape sequence.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › what-are-escape-characters-in-javascript
What are Escape Characters in JavaScript ? - GeeksforGeeks
May 7, 2023 - Example 3: Here by using backslash we will break our string in javascript. ... <!DOCTYPE html> <html> <body> <h1>Escape characters in Javascript</h1> <h2>Breaking the string using backslash</h2> <p id="result"></p> <script> document.getElementById("result").innerHTML = "Hello \world!
🌐
W3Schools
w3schools.com › js › js_strings.asp
JavaScript Strings
1 month ago - Templates were introduced with ES6 (JavaScript 2016). Templates are strings enclosed in backticks (`This is a template string`). Templates allow single and double quotes inside a string: ... The string will be chopped to "We are the so-called ". To solve this problem, you can use an backslash escape character.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-escape-a-string-in-javascript
JavaScript - Escape a String - GeeksforGeeks
July 23, 2025 - The most straightforward way to escape characters is by using backslashes (\). This method allows you to include special characters like quotes (" or '), backslashes, and control characters within a string.
🌐
GitHub
github.com › Manish-Giri › FreeCodeCamp › blob › master › curriculum › challenges › english › 02-javascript-algorithms-and-data-structures › basic-javascript › escape-sequences-in-strings.english.md
FreeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.english.md at master · Manish-Giri/FreeCodeCamp
February 23, 2017 - tests: - text: <code>myStr</code> should not contain any spaces testString: assert(!/ /.test(myStr)); - text: <code>myStr</code> should contain the strings <code>FirstLine</code>, <code>SecondLine</code> and <code>ThirdLine</code> (remember case sensitivity) testString: assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr)); - text: <code>FirstLine</code> should be followed by the newline character <code>\n</code> testString: assert(/FirstLine\n/.test(myStr)); - text: <code>myStr</code> should contain a tab character <code>\t</code> which follows a newline chara
Author   Manish-Giri
🌐
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....