Last updated
Why String Escaping Is Necessary
String escaping converts special characters into sequences that can be safely included in a specific context — JSON, HTML, URLs, SQL, or programming language strings. Without escaping, special characters can break parsing, cause injection vulnerabilities, or corrupt data. Unescaping reverses the process, converting escape sequences back to their original characters.
Common Escape Sequences
| Context | Character | Escaped Form |
|---|---|---|
| JSON/JS | " | " |
| JSON/JS | \ | \ |
| JSON/JS | newline | |
| JSON/JS | tab | |
| HTML | < | < |
| HTML | > | > |
| HTML | & | & |
| HTML | " | " |
| URL | space | %20 |
| URL | & | %26 |
| URL | = | %3D |
JavaScript Escape Functions
// HTML escaping
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// URL encoding
encodeURIComponent('hello world & more');
// → 'hello%20world%20%26%20more'
// JSON string escaping
JSON.stringify('line1
line2 tabbed');
// → '"line1\nline2\ttabbed"'
// Regex escaping (for use in RegExp constructor)
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\]/g, '\$&');
}