JavaScript 6 🧬 escape characters and template literals
Strings in JavaScript can contain special characters and dynamic content. Escape characters let you include special characters, while template literals provide a modern way to work with strings.
A Quick Look at the Examples
let example = "This is a backslash: \\";
console.log(example); // This is a backslash: \
example = 'He said, \'Hello!\'';
console.log(example); // He said, 'Hello!'
example = "She said, \"Hi there!\"";
console.log(example); // She said, "Hi there!"
example = "Line 1\nLine 2";
console.log(example); // Line 1
// Line 2
example = "Hello\rWorld";
console.log(example); // World
example = "Name:\tAlice\nAge:\t25";
console.log(example); // Name: Alice
// Age: 25
example = "This is an octal escape: \101 (\u0041 in hex)";
console.log(example); // This is an octal escape: A
example = "This is a hex escape: \x41 (\u0041 in octal)";
console.log(example); // This is a hex escape: A
example = "This is a Unicode escape: \u03A9 (Omega symbol)";
console.log(example); // This is a Unicode escape: Ω
// Template literals
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!
let message = `
This is a
multi-line string.
`;
console.log(message);
let a = 10;
let b = 5;
console.log(`The sum of ${a} and ${b} is ${a + b}.`);
// The sum of 10 and 5 is 15.
a. Escape Characters
Escape characters are used to represent special characters in strings. They start with a backslash (\) followed by a character.
Common Escape Sequences
| Escape | Name | Description | Example | Output |
|---|---|---|---|---|
\\ | Backslash | Literal backslash | "a\\b" | a\b |
\' | Single quote | Literal single quote | 'He said \'Hi\'' | He said 'Hi' |
\" | Double quote | Literal double quote | "She said \"Hi\"" | She said "Hi" |
\n | New line | Line break | "Line 1\nLine 2" | Line 1 Line 2 |
\r | Carriage return | Returns cursor to line start | "Hello\rWorld" | World |
\t | Tab | Horizontal tab | "Name:\tAlice" | Name: Alice |
\b | Backspace | Backspace character | "abc\bdef" | abdef |
\f | Form feed | Page break | "Page 1\fPage 2" | Page break |
\v | Vertical tab | Vertical tab | "a\vb" | Vertical tab |
\0 | Null | Null character | "a\0b" | a\0b |
Numeric Escape Sequences
| Escape | Name | Description | Example | Output |
|---|---|---|---|---|
\xHH | Hexadecimal | Character by hex code | "\x41" | A |
\uHHHH | Unicode | Character by Unicode code point | "\u0041" | A |
\u{...} | Unicode (ES6) | Extended Unicode | "\u{1F600}" | 😀 |
\NNN | Octal | Character by octal code (deprecated) | "\101" | A |
Examples with Explanations
1. Backslash:
let example = "This is a backslash: \\";
console.log(example); // This is a backslash: \
2. Single quote inside single-quoted string:
let example = 'He said, \'Hello!\'';
console.log(example); // He said, 'Hello!'
3. Double quote inside double-quoted string:
let example = "She said, \"Hi there!\"";
console.log(example); // She said, "Hi there!"
4. New line:
let example = "Line 1\nLine 2";
console.log(example);
// Line 1
// Line 2
5. Carriage return:
let example = "Hello\rWorld";
console.log(example); // World (the \r returns cursor to start, World overwrites Hello)
6. Tab:
let example = "Name:\tAlice\nAge:\t25";
console.log(example);
// Name: Alice
// Age: 25
7. Octal escape:
let example = "This is an octal escape: \101 (\u0041 in hex)";
console.log(example);
// This is an octal escape: A (A is Unicode 0x0041)
8. Hexadecimal escape:
let example = "This is a hex escape: \x41 (\u0041 in octal)";
console.log(example);
// This is a hex escape: A (A is Unicode 0x0041)
9. Unicode escape:
let example = "This is a Unicode escape: \u03A9 (Omega symbol)";
console.log(example);
// This is a Unicode escape: Ω (Greek Capital Letter Omega)
b. Template Literals
Template literals provide a modern way to work with strings. They allow you to embed expressions inside string literals using backticks (`).
Introduced in ES6 (ECMAScript 2015).
Key Features
| Feature | Description | Syntax |
|---|---|---|
| Backticks | Use ` instead of ' or " | `string` |
| String Interpolation | Embed expressions with ${} | `Hello, ${name}!` |
| Multi-line Strings | No need for \n | `Line 1\nLine 2` |
| Expression Evaluation | Any valid JS expression | `${a + b}` |
1. Basic Usage
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!
What happens:
${name}is replaced with the value ofname- The result is a regular string
2. Multi-Line Strings
let message = `
This is a
multi-line string.
`;
console.log(message);
// (newline)
// This is a
// multi-line string.
// (newline)
No need for \n — line breaks are preserved exactly as typed.
3. Expression Interpolation
let a = 10;
let b = 5;
console.log(`The sum of ${a} and ${b} is ${a + b}.`);
// The sum of 10 and 5 is 15.
Any valid JavaScript expression can be used inside ${}:
- Arithmetic:
${a + b} - Function calls:
${getName()} - Ternary:
${isActive ? 'Yes' : 'No'} - Method calls:
${name.toUpperCase()}
4. Template Literals vs Regular Strings
| Aspect | Regular Strings | Template Literals |
|---|---|---|
| Quotes | ' or " | ` |
| Multi-line | Needs \n | ✅ Direct |
| Interpolation | + concatenation | ${} |
| Expression | Not supported | ✅ Supported |
| Escaping quotes | Needed | Not needed (unless backtick) |
Comparison:
// Regular strings
let name = "Alice";
let age = 30;
let message = "Hello, " + name + "! You are " + age + " years old.";
console.log(message);
// Hello, Alice! You are 30 years old.
// Template literals
let message2 = `Hello, ${name}! You are ${age} years old.`;
console.log(message2);
// Hello, Alice! You are 30 years old.
5. Escaping in Template Literals
If you need a literal backtick or ${ in a template literal, escape them:
// Literal backtick
let str = `This is a backtick: \``;
console.log(str); // This is a backtick: `
// Literal ${
let str2 = `This is \${not an expression}`;
console.log(str2); // This is ${not an expression}
// Newline with backslash (line continuation)
let str3 = `This is a \
single line`;
console.log(str3); // This is a single line
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Escape Characters and Template Literals</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
.highlight {
background: #ffc107;
color: #333;
padding: 2px 6px;
border-radius: 4px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Escape Characters and Template Literals</h1>
<div class="demo-box">
<h2>1. Common Escape Characters</h2>
<pre>
<span class="comment">// Backslash</span>
<span class="keyword">let</span> a = <span class="string">"This is a backslash: \\"</span>;
<span class="comment">// Single quote inside single quotes</span>
<span class="keyword">let</span> b = <span class="string">'He said, \'Hello!\''</span>;
<span class="comment">// Double quote inside double quotes</span>
<span class="keyword">let</span> c = <span class="string">"She said, \"Hi there!\""</span>;
<span class="comment">// New line and tab</span>
<span class="keyword">let</span> d = <span class="string">"Name:\tAlice\nAge:\t25"</span>;
</pre>
</div>
<div class="demo-box">
<h2>2. Numeric Escape Sequences</h2>
<pre>
<span class="comment">// Octal escape (deprecated)</span>
<span class="keyword">let</span> octal = <span class="string">"\101"</span>; <span class="comment">// "A" (octal 101 = decimal 65)</span>
<span class="comment">// Hexadecimal escape</span>
<span class="keyword">let</span> hex = <span class="string">"\x41"</span>; <span class="comment">// "A" (hex 41 = decimal 65)</span>
<span class="comment">// Unicode escape</span>
<span class="keyword">let</span> unicode = <span class="string">"\u03A9"</span>; <span class="comment">// "Ω" (Greek Capital Omega)</span>
<span class="comment">// Extended Unicode (ES6)</span>
<span class="keyword">let</span> emoji = <span class="string">"\u{1F600}"</span>; <span class="comment">// "😀"</span>
</pre>
</div>
<div class="demo-box">
<h2>3. Template Literals — Basic Usage</h2>
<pre>
<span class="keyword">let</span> name = <span class="string">"Alice"</span>;
<span class="keyword">let</span> greeting = <span class="string">`Hello, ${name}!`</span>;
console.log(greeting); <span class="comment">// Hello, Alice!</span>
</pre>
</div>
<div class="demo-box">
<h2>4. Template Literals — Multi-Line Strings</h2>
<pre>
<span class="keyword">let</span> message = <span class="string">`
This is a
multi-line string.
`</span>;
console.log(message);
</pre>
</div>
<div class="demo-box">
<h2>5. Template Literals — Expression Interpolation</h2>
<pre>
<span class="keyword">let</span> a = <span class="number">10</span>;
<span class="keyword">let</span> b = <span class="number">5</span>;
console.log(<span class="string">`The sum of ${a} and ${b} is ${a + b}.`</span>);
<span class="comment">// The sum of 10 and 5 is 15.</span>
</pre>
</div>
<div class="demo-box">
<h2>6. Live Output — Escape Characters</h2>
<p>This demo safely demonstrates escape characters:</p>
<div id="output">Loading...</div>
</div>
<div class="demo-box">
<h2>7. Live Output — Template Literals</h2>
<p>This demo shows template literals in action:</p>
<div id="output2">Loading...</div>
</div>
<script>
// ============================================
// Escape Characters — Live Demo
// ============================================
let escapeResults = [];
escapeResults.push('📌 Common Escape Characters:\n');
let backslash = "This is a backslash: \\";
escapeResults.push(' \\\\ → ' + backslash);
let singleQuote = 'He said, \'Hello!\'';
escapeResults.push(' \\\' → ' + singleQuote);
let doubleQuote = "She said, \"Hi there!\"";
escapeResults.push(' \\" → ' + doubleQuote);
let newline = "Line 1\nLine 2";
escapeResults.push(' \\n → ' + newline.replace(/\n/g, ' [newline] '));
let tab = "Name:\tAlice\nAge:\t25";
escapeResults.push(' \\t → ' + tab.replace(/\t/g, ' [tab] ').replace(/\n/g, ' [newline] '));
escapeResults.push('\n📌 Numeric Escape Sequences:\n');
let octal = "\101";
escapeResults.push(' \\101 → ' + octal + ' (octal escape)');
let hex = "\x41";
escapeResults.push(' \\x41 → ' + hex + ' (hex escape)');
let unicode = "\u03A9";
escapeResults.push(' \\u03A9 → ' + unicode + ' (Unicode escape)');
let emoji = "\u{1F600}";
escapeResults.push(' \\u{1F600} → ' + emoji + ' (extended Unicode)');
document.getElementById('output').textContent = escapeResults.join('\n');
// ============================================
// Template Literals — Live Demo
// ============================================
let templateResults = [];
templateResults.push('📌 Basic Interpolation:\n');
let name = "Alice";
let greeting = `Hello, ${name}!`;
templateResults.push(' ' + greeting);
templateResults.push('\n📌 Expression Interpolation:\n');
let a = 10;
let b = 5;
templateResults.push(' The sum of ' + a + ' and ' + b + ' is ' + (a + b) + '.');
templateResults.push(' → Using template: `The sum of ${a} and ${b} is ${a + b}.`');
templateResults.push('\n📌 Method Calls:\n');
let upperName = `Uppercase: ${name.toUpperCase()}`;
templateResults.push(' ' + upperName);
templateResults.push('\n📌 Ternary Operator:\n');
let age = 25;
let status = `Status: ${age >= 18 ? 'Adult' : 'Minor'}`;
templateResults.push(' ' + status);
templateResults.push('\n📌 Multi-line Strings:\n');
let multiLine = `Line 1
Line 2
Line 3`;
templateResults.push(' ' + multiLine.replace(/\n/g, '\n '));
document.getElementById('output2').textContent = templateResults.join('\n');
</script>
</body>
</html>
Quick Reference — Escape Characters
| Escape | Output | Description |
|---|---|---|
\\ | \ | Backslash |
\' | ' | Single quote |
\" | " | Double quote |
\n | (newline) | New line |
\r | (carriage return) | Carriage return |
\t | (tab) | Horizontal tab |
\b | (backspace) | Backspace |
\f | (form feed) | Form feed |
\v | (vertical tab) | Vertical tab |
\0 | (null) | Null character |
\xHH | (char) | Hex character |
\uHHHH | (char) | Unicode character |
\u{...} | (char) | Extended Unicode |
Quick Reference — Template Literals
| Feature | Syntax | Example |
|---|---|---|
| Backticks | `string` | `Hello` |
| Interpolation | ${expression} | `Hello, ${name}!` |
| Multi-line | Direct line breaks | `Line 1\nLine 2` |
| Arithmetic | ${a + b} | `${10 + 5}` → 15 |
| Function call | ${func()} | `${getName()}` |
| Method call | ${obj.method()} | `${name.toUpperCase()}` |
| Ternary | ${condition ? a : b} | `${age >= 18 ? 'Adult' : 'Minor'}` |
| Literal backtick | \` | `Backtick: \ “ |
Literal ${ | \${ | `\${not an expression}` |
String Comparison
| Aspect | Regular Strings | Template Literals |
|---|---|---|
| Quotes | ' or " | ` |
| Multi-line | Needs \n | ✅ Direct |
| Interpolation | + concatenation | ${} |
| Expression | Not supported | ✅ Supported |
| Escaping quotes | Needed | Not needed |
| Introduced | ES1 (1997) | ES6 (2015) |
Best Practices
✅ Do This:
// Use template literals for string interpolation
const greeting = `Hello, ${name}!`;
// Use template literals for multi-line strings
const html = `
<div>
<h1>${title}</h1>
<p>${content}</p>
</div>
`;
// Use escape characters for special characters
const path = "C:\\Users\\Alice\\Documents";
// Use \n for explicit line breaks in regular strings
const message = "Line 1\nLine 2";
❌ Don’t Do This:
// Don't use string concatenation when template literals work
const greeting = "Hello, " + name + "!"; // Use `Hello, ${name}!`
// Don't use \n for multi-line strings
const html = "<div>\n <h1>" + title + "</h1>\n</div>";
// Don't forget to escape backslashes in paths
const path = "C:\Users\Alice"; // ❌ \U is an invalid escape
// Don't use octal escapes (deprecated)
const octal = "\101"; // ⚠️ Deprecated — use \x41 or \u0041
Common Character Codes
| Character | Unicode | Hex | Octal |
|---|---|---|---|
A | \u0041 | \x41 | \101 |
B | \u0042 | \x42 | \102 |
a | \u0061 | \x61 | \141 |
0 | \u0030 | \x30 | \060 |
Ω | \u03A9 | — | — |
é | \u00E9 | — | — |
😀 | \u{1F600} | — | — |
Pro Tip: Template literals (backticks) are the modern way to work with strings — use them for interpolation and multi-line strings. They eliminate the need for string concatenation and \n escapes. Escape characters are still useful when you need special characters in regular strings (like \t for tabs or \\ for file paths). Remember: octal escapes are deprecated — use \xHH (hex) or \uHHHH (Unicode) instead. And for emoji, use the extended Unicode syntax \u{1F600}!
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!