Dev Basics · 5 min read
Escaping Strings for JSON, JavaScript, SQL, Shell, and Regex
Escaping is how you put a character into a string when that character would otherwise mean something else — a quote that would end the string, or a dot that would match any character. Every context has different special characters, which is why one escaping function never fits all.
Try it yourself with the related tool.
Escape a string →Advertisement
JSON and JavaScript
In JSON strings, the double quote and backslash must be escaped as \" and \\, and control characters such as newlines become \n. JavaScript adds escapes for single quotes and, in template literals, backticks and ${. Use JSON.stringify rather than escaping by hand — it handles every case.
SQL
In a SQL string literal, a single quote is escaped by doubling it: 'It''s'. But hand-escaping user input is how SQL injection happens. In application code, always use parameterised queries, so values never become part of the SQL text at all.
Shell
In POSIX shells, single quotes are the safest wrapper: nothing inside them is special. The only problem is a single quote itself, written as '\'' — close the quote, add an escaped quote, reopen it. Double quotes still expand $, backticks, and \. Never paste untrusted input into a shell command; pass it as a separate argument instead.
Regex
In a regular expression, . * + ? ^ $ ( ) [ ] { } | \ and / all have special meanings. To match one literally, put a backslash before it: \. matches a real dot. When building a pattern from user text, escape the whole string first, or a search for "1+1" will behave very strangely.
