The two functions that solve different problems
JavaScript has two URL encoding functions and they are not interchangeable. Getting this wrong is a real source of bugs.
- encodeURI()Encodes a complete URL. Leaves structural characters intact:
: / ? # [ ] @ ! $ & ' ( ) * + , ; =. Use when you have a full URL and need to make it safe for embedding in HTML or an HTTP header. - encodeURIComponent()Encodes a URL component— a query parameter value, a path segment, a fragment. Encodes everything including structural characters. Use this when you're encoding a value that will be placed inside a URL, not the full URL itself. If you use encodeURI() on a query value that contains
&or=, those characters won't be encoded and the URL will be parsed incorrectly.
Common scenarios where encoding goes wrong
- Email in query string
user+tag@example.com— the+in the email becomes a space when decoded if you use encodeURI instead of encodeURIComponent. The email arrives garbled. - Search queries with special charactersA search query containing
&splits into multiple parameters. Always encodeURIComponent() search values. - Redirect URLs as parametersPassing a full URL as a query parameter:
?redirect=https://example.com/path?q=1— the inner URL's?and=will break the outer URL parser unless encodeURIComponent() is used on the value.
