Escape characters in JavaScript are used to represent special characters within strings that would otherwise be difficult or impossible to include directly. These characters allow developers to include quotes, backslashes, newlines, and other special characters within strings.

Because strings must be written within quotes, JavaScript will misunderstand this string:

var x = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

The sequence \"  inserts a double quote in a string:

 

Example

var x = "We are the so-called \"Vikings\" from the north.";
 

The sequence \'  inserts a single quote in a string:

 

Example

var x = 'It\'s alright.';
 

The sequence \\  inserts a backslash in a string:

 

Example

var x = "The character \\ is called backslash.";
 

Six other escape sequences are valid in JavaScript:

Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator

The 6 escape characters above were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.


Explanation of the Complex Example
HTML Structure:

The HTML document includes a head section with metadata, styles, and a script.
The body contains a h1 heading and a div with the class "container" that includes a pre element for displaying preformatted text.


CSS Styling:

Basic styles are applied to the body and the container to improve the appearance.
The pre element has a background color, padding, and a border to make the preformatted text stand out.


JavaScript Function (displayData):
  • Various strings are defined using escape characters: name, address, quote, path, and heart.
  • A template literal (formattedData) is used to format the data, including newlines and other escape sequences.
  • The textContent property of the pre element is set to the formatted data, ensuring that the special characters are correctly displayed.

Additional Advanced Usage of Escape Characters

Escaping Characters in Regular Expressions

When working with regular expressions, certain characters need to be escaped to be treated as literals:
 

let regex = /hello\./;
let str = "hello.";
console.log(regex.test(str)); // Outputs: true
 

In this example, the dot (.) is escaped to match an actual dot character in the string.


Escaping HTML Entities

When dynamically inserting HTML content, it is sometimes necessary to escape HTML entities to prevent code injection and ensure correct rendering:

 
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

let userInput = "<script>alert('XSS');</script>";
let safeInput = escapeHtml(userInput);
document.getElementById("output").innerHTML = safeInput;

This function replaces special HTML characters with their corresponding HTML entities, ensuring that user input is safely displayed.
 



Practice Excercise Practice now