- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript String Escape Characters
JavaScript Strings
JavaScript String Escape Characters
A backslash lets you put special characters inside a string.
Some characters cannot be typed directly inside quotes.
The backslash tells JavaScript to treat the next character specially.
Example
Example
javascript
const text = "She said \"hello\"";
console.log(text);The quotes appear as part of the text.
The Common Escapes
\n is a new line and \t is a tab.
\" and \' are quotes.
\\ is a single backslash.
Syntax
Syntax
javascript
"line one\nline two"The backslash itself never appears in the result.
New Lines
\n creates a real line break inside the string.
Example
Example
javascript
const text = "first\nsecond";
console.log(text.split("\n").length);
console.log(text.length);The newline counts as one character.
Escaping Quotes
Only the quote that ends the string needs escaping.
Example
Example
javascript
const a = "She said \"hello\"";
const b = 'It\'s fine';
const c = "It's fine";
console.log(a);
console.log(b === c);Choosing the other quote style avoids the escape entirely.
The Backslash Itself
Two backslashes produce one, which matters for file paths.
Example
Example
javascript
const path = "C:\\Users\\Ada";
console.log(path);
console.log(path.length);Each double backslash is a single character in the result.
Tabs
\t is useful for lining up console output.
Example
Example
javascript
console.log("name\tage");
console.log("Ada\t36");Tabs are for plain text; use CSS for alignment on a page.
Template Literals Need Fewer Escapes
A real line break works directly inside backticks.
Only backticks and ${'$'}{ need escaping there.
Example
Example
javascript
const text = `first
second`;
console.log(text.split("\n").length);The output is 2, with no \n needed.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Escape Characters</title>
</head>
<body>
<h1>Escape Characters</h1>
<pre id="out"></pre>
<script>
const text = "She said \"hello\"\nOn a new line\tafter a tab\nPath: C:\\Users\\Ada";
document.getElementById("out").textContent = text;
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try removing an escape:
Delete one backslash before a quote and see the syntax error.
Important Points
- A backslash escapes the character after it.
\nis a new line and\tis a tab.- Escape only the quote that would end the string.
\\produces a single backslash.- Template literals need far fewer escapes.
Conclusion
Escapes let a string contain characters you cannot type directly.
Most of the time, choosing the other quote style is simpler.
Backticks remove the need for the most common escape of all.
