Expert ReviewedUpdated 2025utility
utility
9 min readMay 28, 2025Updated Feb 24, 2026

URL Encoding Explained: When and How to Encode URLs Properly

Master URL encoding for web development. Learn when to use encodeURIComponent vs encodeURI, handle special characters, and avoid common URL encoding mistakes.

Ever clicked a link with %20 or %3D in it and wondered what those strange codes mean? That's URL encoding in action. It's how the web handles spaces, special characters, and non-ASCII text in URLs. Get it wrong, and your links break, forms fail, or APIs return errors. This guide explains exactly when and how to encode URLs properly.

Key Takeaways

  • 1
    URL encoding converts unsafe characters to %XX format (hex ASCII/UTF-8 values)
  • 2
    Use encodeURIComponent for query values and path segments; encodeURI for full URLs (rarely needed)
  • 3
    Never double-encode: encode raw values once, at the final step before sending
  • 4
    Space can be + (forms only) or %20 (works everywhere)—use %20 when in doubt
  • 5
    Modern approach: Use URL and URLSearchParams APIs for automatic, correct encoding

1What Is URL Encoding?

URL encoding (also called percent-encoding) converts characters that aren't allowed in URLs into a safe format. Each unsafe character becomes a percent sign followed by two hexadecimal digits representing its ASCII/UTF-8 value.
Example: Basic Encoding

Scenario

Encode a search query with spaces and special characters

Solution

"Hello World!" → "Hello%20World%21" — Space becomes %20 (hex 20 = decimal 32, the ASCII code for space). Exclamation mark becomes %21.

Common URL-encoded characters
CharacterEncodedReason
Space%20 or +Not allowed in URLs
&%26Query string separator
=%3DKey-value separator
?%3FQuery string start
#%23Fragment identifier
/%2FPath separator
+%2BOften means space in forms

2When to Encode (and When Not To)

The tricky part of URL encoding is knowing when to apply it. Encoding the wrong parts of a URL breaks it just as badly as not encoding the right parts.
What to encode in different URL parts
URL PartEncode?Example
Protocol (https://)Neverhttps:// stays as-is
Domain (example.com)NeverUse Punycode for internationalized domains
Path segmentsEncode values/users/John%20Doe
Query parameter namesEncodemy%20key=value
Query parameter valuesAlways encodesearch=hello%20world
Fragment (#section)Encode value#section%20name
Never double-encode! If a value is already encoded (%20), encoding it again produces %2520 (the percent sign gets encoded). Always work with raw values and encode once at the end.

URL Encoding in JavaScript

JavaScript provides multiple encoding functions. Using the wrong one is a common source of bugs.
JavaScript encoding functions
FunctionUse ForDoes NOT Encode
encodeURIComponent()Query params, path segmentsA-Z a-z 0-9 - _ . ! ~ * ' ( )
encodeURI()Full URLs (rarely needed)All above + : / ? # [ ] @ ! $ & ' ( ) * + , ; =
escape() ❌DEPRECATED - never useInconsistent, doesn't handle UTF-8
Example: Building a URL Correctly

Scenario

Create a search URL with user input that might contain special characters

Solution

const url = `https://api.example.com/search?q=${encodeURIComponent(userInput)}&page=1`; — Only encode the value, not the whole URL. The ? and & must stay unencoded.

Modern JavaScript: Use the URL and URLSearchParams APIs. They handle encoding automatically: new URL("https://example.com"); url.searchParams.set("q", "hello world");

4Common URL Encoding Mistakes

These bugs appear constantly in production code. Learn to recognize and avoid them.
URL encoding mistakes to avoid
MistakeProblemFix
Double encoding%20 becomes %2520Encode once, at the end
Encoding whole URLhttps%3A%2F%2F breaks URLOnly encode values, not structure
Not encoding at allSpaces break URL, & splits valuesAlways encode user input
Using encodeURI for paramsDoesn't encode &, =, ?Use encodeURIComponent
Forgetting + vs %20Plus decoded as space in formsUse %20 in path, + or %20 in query
Mixing encoded/decodedInconsistent handlingDecode on receive, encode on send
Example: The Double-Encoding Bug

Scenario

User searches for "50% off" — you encode it, store it, then encode again when building the URL

Solution

First encode: "50%25%20off" (correct). Second encode: "50%2525%2520off" (broken). Solution: Track whether data is encoded or raw. Encode only once.

Special Cases & Edge Cases

Some encoding scenarios require special handling beyond basic encodeURIComponent.
  • **Unicode/Emoji** – Encoded as UTF-8 bytes: 🎉 → %F0%9F%8E%89
  • **Plus sign (+)** – Encode as %2B if you want a literal plus, not a space
  • **Slash in path** – Use %2F only if slash is data, not a path separator
  • **Reserved characters in values** – Always encode: & = ? # when they're data
  • **Form data (application/x-www-form-urlencoded)** – Space as +, not %20
  • **RFC 3986 strict** – Also encode ! ' ( ) * for maximum compatibility
The + vs %20 difference matters! In query strings, + traditionally means space (from HTML forms). In paths, + is a literal plus. When in doubt, use %20 — it works everywhere.

6URL Encoding for APIs

API calls frequently involve URL encoding. Here's how to handle common scenarios correctly.
API URL encoding patterns
ScenarioApproach
Query parametersAlways encodeURIComponent values
Path parametersEncode each segment separately
JSON in URLJSON.stringify then encodeURIComponent
Arrays in queryids=1&ids=2 or ids=1,2 or ids=[1,2] (API-specific)
OAuth tokensEncode before including in URL
Webhook URLsFull URL as parameter: callback=https%3A%2F%2F...
Example: Passing a URL as a Parameter

Scenario

Call an API with a callback URL: https://api.com/share?url=https://mysite.com/page?id=123

Solution

Encode the callback: /share?url=https%3A%2F%2Fmysite.com%2Fpage%3Fid%3D123 — The inner ? and = must be encoded so they're not parsed as part of the outer query string.

7Decoding URLs

Decoding reverses the encoding process. Use the right function and handle errors gracefully.
JavaScript decoding functions
FunctionUse ForNotes
decodeURIComponent()Query params, path segmentsThrows on malformed input
decodeURI()Full URLs (rare)Doesn't decode reserved chars
URLSearchParams.get()Query paramsAuto-decodes, handles + as space
unescape() ❌DEPRECATEDNever use
decodeURIComponent throws URIError on invalid sequences like %ZZ or truncated %2. Always wrap in try-catch when processing untrusted input.

Encode & Decode URLs Online

Use our free URL Encoder tool to quickly encode or decode URLs, query strings, and special characters—all processed locally in your browser.

Open URL Encoder

URL Encoding in Other Languages

Every programming language has URL encoding functions. Here's a quick reference.
URL encoding across languages
LanguageEncodeDecode
Pythonurllib.parse.quote(s, safe="")urllib.parse.unquote(s)
PHPrawurlencode($s)rawurldecode($s)
JavaURLEncoder.encode(s, "UTF-8")URLDecoder.decode(s, "UTF-8")
C#Uri.EscapeDataString(s)Uri.UnescapeDataString(s)
RubyCGI.escape(s)CGI.unescape(s)
Gourl.QueryEscape(s)url.QueryUnescape(s)
PHP has urlencode (spaces as +) and rawurlencode (spaces as %20). Use rawurlencode for path segments, urlencode for form data.

Frequently Asked Questions

What's the difference between %20 and + for spaces?
Both represent spaces, but in different contexts. %20 works everywhere and is the standard RFC 3986 encoding. + is only valid in query strings (application/x-www-form-urlencoded, from HTML forms). In URL paths, + is a literal plus sign. When in doubt, use %20.
Why do I see %2F instead of / in some URLs?
The forward slash is a path separator in URLs. If you need a literal slash as data (like in a filename), it must be encoded as %2F. Otherwise the server interprets it as a directory separator. Example: /files/path%2Fto%2Ffile.txt passes "path/to/file.txt" as a single segment.
Should I encode URLs for SEO?
Search engines handle encoded URLs fine, but human-readable URLs are better for usability. Use hyphens instead of spaces (/my-page not /my%20page). Most web frameworks do this automatically. Only encode special characters that would break the URL.
How do I encode a full URL that includes query parameters?
Don't encode the whole URL at once. Parse it into parts, encode only the values, then reassemble. In JavaScript: use the URL API with url.searchParams.set() which handles encoding automatically. Or encode values individually with encodeURIComponent before concatenating.
What characters are "safe" and don't need encoding?
Unreserved characters (RFC 3986) are safe anywhere: A-Z, a-z, 0-9, hyphen (-), underscore (_), period (.), tilde (~). Reserved characters like ? & = / # have special meaning and must be encoded when used as data. Encode everything else to be safe.