JavaScript URL Functions
JavaScript provides four functions for URL encoding/decoding, and using the wrong one is a common source of bugs.
encodeURI vs encodeURIComponent
| Function | Encodes | Use Case |
|---|
encodeURI | Spaces, non-ASCII | Full URLs |
|---|
encodeURIComponent | All special chars | URL parameters |
|---|
encodeURI
Use for encoding complete URLs. Preserves URL structure characters.
encodeURI("https://example.com/path with spaces")
// "https://example.com/path%20with%20spaces"
// Does NOT encode: ; / ? : @ & = + $ , #
encodeURI("https://example.com?name=John&age=30")
// "https://example.com?name=John&age=30" (unchanged)
encodeURIComponent
Use for encoding values to be placed IN a URL. Encodes everything except alphanumeric and - _ . ! ~ * ' ( ).
encodeURIComponent("hello world")
// "hello%20world"
encodeURIComponent("name=John&age=30")
// "name%3DJohn%26age%3D30"
// Building a URL with user input
const userQuery = "cats & dogs";
const url = https://api.com/search?q=${encodeURIComponent(userQuery)};
// "https://api.com/search?q=cats%20%26%20dogs"
The URL API (Modern Approach)
// Building URLs safely
const url = new URL("https://example.com/search");
url.searchParams.set("q", "cats & dogs");
url.searchParams.set("page", "1");
console.log(url.toString());
// "https://example.com/search?q=cats+%26+dogs&page=1"
// Parsing URLs
const parsed = new URL("https://example.com/path?name=John");
console.log(parsed.hostname); // "example.com"
console.log(parsed.pathname); // "/path"
console.log(parsed.searchParams.get("name")); // "John"