Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Escape characters in JavaScript
Escape characters are special characters that require a backslash (\) prefix to be displayed literally in JavaScript strings. Without escaping, these characters have special meanings that could break your code or produce unexpected results.
Common Escape Characters
| Code | Result | Description |
|---|---|---|
| ' | Single quote | Allows single quotes inside single-quoted strings |
| " | Double quote | Allows double quotes inside double-quoted strings |
| \ | Backslash | Displays a literal backslash character |
| New Line | Creates a line break | |
| \t | Tab | Creates horizontal spacing |
| \r | Carriage Return | Returns cursor to line beginning |
| \b | Backspace | Moves cursor back one position |
| \f | Form Feed | Page break character |
| \v | Vertical Tab | Vertical spacing |
Example: Using Quote Escapes
Escape Characters Demo
Example: Newlines and Tabs
// Using newline and tab escapes let poem = "Roses are red,\nViolets are blue,
\tJavaScript is awesome,
\tAnd so are you!"; console.log(poem); // Using backslash escape let filePath = "C:\Users\John\Documents\file.txt"; console.log(filePath);
Roses are red, Violets are blue, JavaScript is awesome, And so are you! C:\Users\John\Documents\file.txt
Example: Multiple Escapes in One String
let complexString = 'Hello World "This" is some sample \ Text 'quoted' text';
console.log(complexString);
// Breaking it down:
console.log('Escaped double quotes: "This"');
console.log('Escaped backslash: \');
console.log('Escaped single quote: 'quoted'');
Hello World "This" is some sample \ Text 'quoted' text Escaped double quotes: "This" Escaped backslash: \ Escaped single quote: 'quoted'
When to Use Escape Characters
Escape characters are essential when:
- Including quotes within quoted strings
- Displaying literal backslashes (like file paths)
- Adding formatting like line breaks and tabs
- Preventing syntax errors in string literals
Conclusion
Escape characters allow you to include special characters literally in JavaScript strings. The most commonly used are ', ", \,
, and \t for quotes, backslashes, and formatting.
Advertisements
