Back to Blog

Understanding URL Encoding in Web Development

February 12, 2025 · 6 min read

What is URL Encoding?

URL encoding, also known as percent-encoding, is a mechanism for translating characters into a format that can be safely transmitted over the internet. URLs can only be sent over the internet using the ASCII character set, so any characters outside of this set — or characters that have special meaning in URLs — must be encoded.

The encoding works by replacing unsafe characters with a % sign followed by two hexadecimal digits representing the ASCII code of the character. For example, a space becomes%20.

Why is URL Encoding Necessary?

URLs have a strict syntax defined by RFC 3986. Certain characters serve special purposes:

  • ? — Separates the path from query parameters
  • & — Separates multiple query parameters
  • = — Assigns values to parameters
  • # — Indicates a fragment identifier
  • / — Separates path segments

If your data contains any of these characters, they must be percent-encoded to prevent the browser from misinterpreting them as structural elements of the URL.

Common Characters That Need Encoding

CharacterEncodedCommon Use
Space%20 or +Search queries
!%21Text values
#%23Hashtags, fragments
$%24Currency values
&%26Query separators
+%2BMath expressions
@%40Email addresses

URL Encoding in JavaScript

JavaScript provides several built-in functions for URL encoding:

// encodeURIComponent — for encoding query parameter values
const query = encodeURIComponent("hello world & goodbye");
// Result: "hello%20world%20%26%20goodbye"

// encodeURI — for encoding a full URI (preserves structural characters)
const url = encodeURI("https://example.com/path?q=hello world");
// Result: "https://example.com/path?q=hello%20world"

// decodeURIComponent — to decode back
const decoded = decodeURIComponent("hello%20world");
// Result: "hello world"

encodeURI vs encodeURIComponent

This distinction is critical and a common source of bugs:

  • encodeURI: Encodes a full URI. It does not encode structural characters like :, /,?, &, or =.
  • encodeURIComponent: Encodes a single component (like a query parameter value). It encodes everything except letters, digits, and a few safe characters.

Rule of thumb: Use encodeURIComponent for individual values, and encodeURI only when encoding a complete URL string.

Common Mistakes

  • Double encoding — encoding an already-encoded string produces garbled output like %2520.
  • Using encodeURI when encodeURIComponent is needed.
  • Forgetting to decode URL-encoded data on the server side before processing it.
  • Not encoding user-supplied data in URLs, leading to injection vulnerabilities.

Try it yourself

Encode and decode URLs with automatic query parameter parsing.

Open Tool