Escaping Quotes Inside Strings
Master the techniques for including quotation marks inside string literals. Covers escaping single and double quotes with backslashes, alternating delimiters, and language-specific quoting rules.
Detailed Explanation
Escaping Quotes in Strings
When a string is delimited by a particular quote character, including that same character inside the string requires special handling. Without escaping, the parser would interpret the inner quote as the end of the string, causing a syntax error.
Backslash Escaping
The most common approach is prefixing the quote with a backslash:
const single = 'It\'s a test';
const double = "She said \"hello\"";
The backslash tells the parser to treat the following quote as a literal character rather than a string terminator.
Alternating Delimiters
Many languages allow both single and double quotes. You can avoid escaping by choosing the delimiter that does not appear in the content:
message = "It's a test" # no escaping needed
message = 'She said "hello"' # no escaping needed
Language-Specific Approaches
- Python: Triple-quoted strings (
"""..."""or'''...''') can contain unescaped single or double quotes. - JavaScript / TypeScript: Template literals (
\...`) avoid the need to escape single or double quotes entirely. Only backticks and${` need escaping inside them. - SQL: Standard SQL escapes a single quote by doubling it:
'O''Brien'. Some databases also accept backslash escaping. - C# / Java: Only double-quoted strings are available for
Stringtypes, so double quotes must always be backslash-escaped.
Nested Quoting Challenges
When generating code that itself contains strings, quote escaping can stack up:
// JavaScript string containing a JSON string containing a value with quotes
const json = "{\"name\": \"O'Brien\"}";
Each nesting level multiplies the escaping. Template literals and raw strings reduce this complexity significantly.
HTML Attribute Quoting
In HTML, attribute values can use either single or double quotes. If the value contains one type, wrap it with the other:
<div title="It's here">
<div title='She said "hello"'>
Alternatively, use HTML entities: " for double quotes and ' for single quotes.
Use Case
Quote escaping is encountered daily in web development when embedding strings in HTML attributes, constructing SQL queries, generating JSON data, writing shell scripts with quoted arguments, and building code generators or templating systems. Incorrect escaping is also a leading cause of SQL injection and XSS vulnerabilities.