URL Encoding in JavaScript
JavaScript provides native, built-in methods for encoding and decoding URLs. Understanding how to use these correctly is a fundamental skill for frontend and Node.js developers.
The Three Encoding Methods
Historically, JavaScript had three methods for encoding. Today, only two are recommended:
- encodeURI(): Use this to encode an entire, complete URL. It ignores structural characters like
?and/. - encodeURIComponent(): Use this to encode specific data values. It encodes almost everything.
- escape(): Deprecated. Never use this in modern code. It does not handle Unicode correctly.
Building URLs with URLSearchParams
The most robust way to handle URL parameters in modern JavaScript is the URLSearchParams API. It completely removes the need to call encodeURIComponent manually.
const baseUrl = 'https://api.urlencoder.com/search';
const params = new URLSearchParams({
query: 'black & white',
category: 'shoes',
page: 1
});
const fullUrl = `${baseUrl}?${params.toString()}`;
// The API automatically handles the percent-encoding for the ampersand!
Decoding in JavaScript
To decode strings, you use the inverse functions: decodeURI() and decodeURIComponent(). If a string is improperly encoded, calling these functions will throw a URIError, so it is often wise to wrap decoding logic in a try-catch block when handling unknown user input.