URL Encoding Explained: Handling Special Characters in Web

URL bar showing encoded characters

Type "hello world" into Google, and the URL becomes "hello%20world". Why? Because URLs have a specific grammar, and spaces aren't allowed. URL encoding (percent-encoding) solves this.

The Rules

Every character in a URL either has special meaning or must be encoded. Letters, numbers, hyphens, underscores, and tildes are generally safe. Everything else gets encoded as %XX, where XX is the hexadecimal ASCII code.

Space = 32 = 0x20 = %20. Simple enough, right?

When Encoding Matters

Query parameters are the most common place you'll encounter URL encoding. If you have ?name=John Smith, the space must be encoded. Always use your language's built-in URL encoding functions—don't do it manually.

Modern JavaScript has encodeURIComponent() for this exact purpose. PHP has urlencode(). Python has urllib.parse.quote(). Use them.

The Difference Between encodeURI and encodeURIComponent

encodeURI() leaves certain characters unencoded (slashes, colons, etc.) because they're needed in full URLs. encodeURIComponent() encodes everything, used for query parameter values.

Related Tools

URL Encoder/Decoder

Encode and decode URL strings.