How to Escape Special Characters in JavaScript

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:

  1. Backslash (\): Escaped as \\
  2. Single quote (‘): Escaped as \’
  3. Double quote (“): Escaped as \”
  4. Line feed: Escaped as \n
  5. Carriage return: Escaped as \r
  6. Tab: Escaped as \t
  7. Backspace: Escaped as \b
  8. 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:

  1. Double quote (“) and single quote (‘): You don’t need to escape these within a template literal.
  2. 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!