algorithm
character encoding
programming
escape sequence
coding basics

What's the simplest algorithm to escape a single character?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The simplest character escaping algorithm is prefix-based escaping: prepend a designated escape character (usually backslash \) before any character that has special meaning. To escape the string, scan each character — if it is a special character or the escape character itself, insert the escape prefix before it. To unescape, scan for the escape prefix and remove it while keeping the following character as literal. This two-pass algorithm handles any set of special characters.

The Basic Algorithm

python
1def escape(text, special_chars, escape_char='\\'):
2    """Escape special characters by prefixing with escape_char."""
3    result = []
4    for char in text:
5        if char == escape_char or char in special_chars:
6            result.append(escape_char)
7        result.append(char)
8    return ''.join(result)
9
10def unescape(text, escape_char='\\'):
11    """Remove escape prefixes, restoring original characters."""
12    result = []
13    i = 0
14    while i < len(text):
15        if text[i] == escape_char and i + 1 < len(text):
16            result.append(text[i + 1])  # Take the next char literally
17            i += 2
18        else:
19            result.append(text[i])
20            i += 1
21    return ''.join(result)
22
23# Example
24original = 'price is $10 (50% off)'
25escaped = escape(original, special_chars={'$', '(', ')', '%'})
26print(escaped)   # price is \$10 \(50\% off\)
27print(unescape(escaped))  # price is $10 (50% off)

Why Escape the Escape Character?

The escape character itself must be escaped, otherwise you cannot represent it literally:

python
1original = r'path\to\file'
2escaped = escape(original, special_chars=set())  # No special chars, but \ is always escaped
3print(escaped)   # path\\to\\file
4print(unescape(escaped))  # path\to\file

Without this rule, \n would be ambiguous — is it an escaped n (the letter) or a literal backslash followed by n?

Language-Specific Examples

Python

python
1# Built-in escaping for strings
2text = 'She said "hello"'
3escaped = text.replace('"', '\\"')
4# She said \"hello\"
5
6# For regex special characters
7import re
8pattern = re.escape('price is $10.00 (USD)')
9# price\ is\ \$10\.00\ \(USD\)
10
11# For SQL (use parameterized queries instead)
12# cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))

JavaScript

javascript
1// Escape HTML special characters
2function escapeHtml(text) {
3    const map = {
4        '&': '&amp;',
5        '<': '&lt;',
6        '>': '&gt;',
7        '"': '&quot;',
8        "'": '&#039;'
9    };
10    return text.replace(/[&<>"']/g, char => map[char]);
11}
12
13// Escape regex special characters
14function escapeRegex(string) {
15    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
16}
17
18// Escape for JSON strings
19const escaped = JSON.stringify("line1\nline2");
20// "\"line1\\nline2\""

C / C++

c
1// Backslash escaping in string literals
2char *str = "She said \"hello\"";    // She said "hello"
3char *path = "C:\\Users\\file.txt";  // C:\Users\file.txt
4char *newline = "line1\nline2";      // line1<newline>line2

SQL

sql
1-- Escape single quotes by doubling them
2SELECT * FROM users WHERE name = 'O''Brien';
3
4-- MySQL: backslash escaping
5SELECT * FROM users WHERE name = 'O\'Brien';
6
7-- Best practice: use parameterized queries instead of manual escaping

URL Encoding (Percent Encoding)

A different escaping scheme where special characters are replaced with %XX (hex):

python
1from urllib.parse import quote, unquote
2
3text = "hello world & foo=bar"
4encoded = quote(text)
5print(encoded)   # hello%20world%20%26%20foo%3Dbar
6print(unquote(encoded))  # hello world & foo=bar

HTML Entity Escaping

Replaces characters with named or numeric entities:

python
1import html
2
3text = '<script>alert("xss")</script>'
4escaped = html.escape(text)
5print(escaped)  # &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;
6print(html.unescape(escaped))  # <script>alert("xss")</script>

Comparison of Escaping Strategies

StrategyEscape FormatExample
Backslash prefix`` + char\" for "
Doublingchar + char'' for ' (SQL)
Percent encoding% + hex%20 for space
HTML entities&name; or &#num;&amp; for &
Caret (CMD)^ + char^ | for|

Common Pitfalls

  • Forgetting to escape the escape character: If \ is the escape character but is not itself escaped, the string a\b is ambiguous (is b being escaped or is this a literal backslash?). Always escape the escape character first.
  • Double escaping: Escaping an already-escaped string produces \\\" instead of \". Track whether data is already escaped and never escape twice. This is a frequent bug when passing data through multiple layers (database, API, template).
  • Using string escaping instead of parameterized queries for SQL: Manual SQL escaping is fragile and language-dependent. Always use parameterized queries (? or %s placeholders) to prevent SQL injection.
  • Escaping for the wrong context: HTML escaping (&lt;) does not protect against JavaScript injection in onclick attributes. URL encoding does not help in HTML body text. Each context (HTML, JS, URL, SQL, shell) requires its own escaping rules.
  • Not unescaping on the receiving end: If you escape data before sending, the receiver must unescape it. Displaying Hello\ World to a user because you forgot to unescape is a common presentation bug.

Summary

  • The simplest escaping algorithm prefixes special characters with an escape character (usually \)
  • Always escape the escape character itself to avoid ambiguity
  • Use language-built-in functions (re.escape, html.escape, JSON.stringify, encodeURIComponent) instead of manual implementations
  • Different contexts (HTML, SQL, URL, shell) require different escaping rules — never mix them
  • For SQL, always use parameterized queries instead of manual character escaping

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.