To escape special characters in JavaScript, use the “\ (backslash)” character. The backslash suggests that the next character should be treated as a literal character rather than a special character or string delimiter.
Here’s a brief overview of how to escape some common characters in JavaScript strings:
- Backslash (\): Escaped as \\
- Single quote (‘): Escaped as \’
- Double quote (“): Escaped as \”
- Line feed: Escaped as \n
- Carriage return: Escaped as \r
- Tab: Escaped as \t
- Backspace: Escaped as \b
- Form feed: Escaped as \f
Here is an example of escaping a string:
let quote = "Warren said, \"He made money thorugh stock market!\"";
console.log(quote);
let Independence = 'It\'s an Independence day';
console.log(Independence);
Output
Warren said, "He made money thorugh stock market!"
It's a Independence day
How to Use Template Literals to Escape a String in JavaScript
Template literals are a feature in ES6 (ES2015) and later versions of JavaScript that allow you to create more readable and flexible strings. They use backticks (`) as delimiters, and any content between the backticks is treated as a string. This includes line breaks and embedded expressions.
With template literals, the need to escape some characters is reduced but not eliminated. For example:
- Double quote (“) and single quote (‘): You don’t need to escape these within a template literal.
- Line breaks: You can include line breaks directly without needing to use \n.
However, if you want to include a backtick inside a template literal, you’ll still need to escape it using a backslash (\).
Here are some examples:
Basic Usage
Example 1
let str = `This is a template literal.`;
console.log(str)
Output
This is a template literal.
Example 2
let data = `Warren said, "He made money through stock market!"`;
console.log(data);
Output
Warren said, "He made money through stock market!"
Embedded Expressions
You can embed expressions inside ${…} within a template literal:
let main_name = "Krunal";
let greeting = `Hello, ${main_name}!`;
console.log(greeting);
Output
Hello, Krunal!
Complete Example
let example1 = 'This is a backslash: \\';
let example2 = 'This is a single quote: \'';
let example3 = 'This is a double quote: \"';
let example4 = 'New line:\nSecond line.';
console.log(example1)
console.log(example2)
console.log(example3)
console.log(example4)
Output
This is a backslash: \
This is a single quote: '
This is a double quote: "
New line:
Second line.
That’s it!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.