In JavaScript, you can use the encodeURIComponent, encodeURI, decodeURIComponent, and decodeURI functions to encode or decode URLs or their components.
1. Encoding a URL
Use encodeURI or encodeURIComponent to encode URLs or parts of them.
encodeURI: Encodes a full URL, leaving special characters like:,/,?,&, and=intact.encodeURIComponent: Encodes individual components of a URL, including all special characters.
// Example of encodeURI const url = "https://example.com/page?name=John Doe&age=30"; const encodedURL = encodeURI(url); console.log(encodedURL); // Output: https://example.com/page?name=John%20Doe&age=30 // Example of encodeURIComponent const queryParam = "John Doe"; const encodedParam = encodeURIComponent(queryParam); console.log(encodedParam); // Output: John%20Doe
2. Decoding a URL
Use decodeURI or decodeURIComponent to decode previously encoded URLs or components.
decodeURI: Decodes a full URL that was encoded usingencodeURI.decodeURIComponent: Decodes a URL component that was encoded usingencodeURIComponent.
// Example of decodeURI const encodedURL = "https://example.com/page?name=John%20Doe&age=30"; const decodedURL = decodeURI(encodedURL); console.log(decodedURL); // Output: https://example.com/page?name=John Doe&age=30 // Example of decodeURIComponent const encodedParam = "John%20Doe"; const decodedParam = decodeURIComponent(encodedParam); console.log(decodedParam); // Output: John Doe
3. Key Differences Between encodeURI and encodeURIComponent
| Function | Use Case | Encodes Special Characters Like :, /, ?, &, = |
encodeURI | Full URL (leaves URL syntax characters) | No |
| encodeURIComponent | URL components (encodes everything) | Yes |
4. Example: Building a Query String
When constructing a query string for a URL, you can encode each parameter using encodeURIComponent:
const baseURL = "https://example.com/search";
const params = {
query: "JavaScript tips",
page: 2,
sort: "relevance"
};
// Construct query string
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join("&");
const fullURL = `${baseURL}?${queryString}`;
console.log(fullURL);
// Output: https://example.com/search?query=JavaScript%20tips&page=2&sort=relevance
