How do you encode or decode a URL in JavaScript?
As a web developer, working with URLs is essential for building dynamic web applications that interact with APIs, handle redirects, and more. In this response, we'll discuss how to encode and decode URLs using JavaScript.
Encoding a URL
To encode a URL, you can use the encodeURIComponent()
function in JavaScript. This function takes a string as input and returns its encoded version.
const url = "https://example.com/path?param=value";
const encodedUrl = encodeURIComponent(url);
console.log(encodedUrl); // Output: https%3A%2F%2Fexample.com%2Fpath%3Fparam%3Dvalue
// Alternatively, you can use the URL class and its `href` property
const url = new URL('https://example.com/path?param=value');
const encodedUrl = url.href;
console.log(encodedUrl); // Output: https://example.com/path?param=value
Note that encodeURIComponent()
encodes special characters like spaces, query parameters, and other non-alphanumeric characters using the %
escape sequence.
Decoding a URL
To decode a URL, you can use the decodeURIComponent()
function in JavaScript. This function takes a string as input and returns its decoded version.
const encodedUrl = "https%3A%2F%2Fexample.com%2Fpath%3Fparam%3Dvalue";
const decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl); // Output: https://example.com/path?param=value
// Alternatively, you can use the URL class and its `href` property
const url = new URL('https://example.com/path%20with%20spaces');
const decodedUrl = url.href;
console.log(decodedUrl); // Output: https://example.com/path with spaces
Note that decodeURIComponent()
decodes only the %
escape sequence, so you need to use it in combination with encodeURIComponent()
when working with URLs.
Example Use Cases
Here's an example of how encoding and decoding can be used in a real-world scenario:
// Encoding a URL with query parameters
const originalUrl = "https://example.com/api/data?name=John+Doe&age=30";
const encodedUrl = encodeURIComponent(originalUrl);
console.log(encodedUrl); // Output: https%3A%2F%2Fexample.com%2Fapi%2Fdata%3Fname%3DJohn+Doe%26age%3D30
// Decoding the URL
const decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl); // Output: https://example.com/api/data?name=John Doe&age=30
// Using encoded and decoded URLs in an HTTP request
const encodedUrl = encodeURIComponent('https://example.com/api/data');
fetch(encodedUrl)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
By following these steps, you can ensure that your web applications handle URLs correctly and securely.