JavaScript String Escape
Escape and unescape special characters in JavaScript strings, including quotes, newlines and control characters
About JavaScript String Escaping
JavaScript string escaping is the process of converting special characters in a string into escape sequences. This is essential for safely representing strings containing quotes, newlines, and other control characters in JavaScript code.
When you need to embed user input in JavaScript code, process JSON data, or generate dynamic code, proper string escaping can prevent syntax errors and potential security issues.
Why Escape?
- Include quote characters in string literals
- Represent newlines, tabs, and other invisible characters
- Safely embed user input in code
- Generate valid JavaScript code snippets
- Process string data from external sources
Common Use Cases
Dynamic Code Generation
When dynamically building JavaScript code strings, special characters must be properly escaped to avoid syntax errors.
Handling User Input
When embedding user input into JavaScript code, escaping can prevent code injection attacks.
Data Serialization
When serializing data to string format, escaping ensures data integrity.
Template String Processing
When using backticks or ${} in template strings, these characters may need to be escaped.
Escape Rules Reference
| Original Character | Escape Sequence | Description |
|---|---|---|
| \ | \\ | Backslash itself |
| ' | \' | Single quote |
| " | \" | Double quote |
| LF | \n | Line Feed |
| CR | \r | Carriage Return |
| TAB | \t | Horizontal Tab |
| BS | \b | Backspace |
| FF | \f | Form Feed |
| VT | \v | Vertical Tab |
| NUL | \0 | NULL character |
| U+XXXX | \uXXXX | Unicode character (4-digit hex) |
| 0xNN | \xNN | Hexadecimal character (2-digit) |
Usage Tips
- In single-quoted strings, only escape single quotes; in double-quoted strings, only escape double quotes
- Template strings (backticks) require escaping backticks and ${
- Regular expression literals may require additional escaping
- JSON strings can only use double quotes and must escape double quotes and control characters