Uniform Resource Identifiers (URIs) only permit a limited subset of ASCII characters. When URLs include query parameters containing spaces, ampersands, slashes, or international text, these characters must be converted into safe percent-encoded representations. In this guide, you will learn how URL encoding works and how to encode parameters correctly in JavaScript.
What is Percent-Encoding (URL Encoding)?
Percent-encoding (defined in RFC 3986) replaces non-permitted or reserved characters in a URL with a percent sign (%) followed by a two-digit hexadecimal representation of the character's UTF-8 byte value. For example:
- Space: becomes
%20(or+in application/x-www-form-urlencoded form data) - Ampersand (&): becomes
%26 - Question mark (?): becomes
%3F - Slash (/): becomes
%2F - Equals sign (=): becomes
%3D
encodeURI vs. encodeURIComponent: Key Differences
JavaScript provides two built-in global functions for encoding URLs. Understanding the difference between them is crucial to prevent broken links and API bugs:
encodeURI(fullUrl): Used for an entire URL. It preserves protocol and path delimiters like:,/,?,#, and&while escaping invalid characters like spaces.encodeURIComponent(param): Used for individual query parameter values or keys. It encodes all delimiters, including/,?,&, and=, ensuring that values don't inadvertently split the query string.
Code Examples in JavaScript
// 1. Encoding an entire URL with encodeURI
const fullUrl = "https://sylvaera.com/search?topic=machine learning";
console.log(encodeURI(fullUrl));
// Output: "https://sylvaera.com/search?topic=machine%20learning"
// 2. Encoding query parameters with encodeURIComponent
const paramKey = "filter";
const paramValue = "status=active&type=prod/test";
const safeUrl = `https://api.sylvaera.com/v1/items?${encodeURIComponent(paramKey)}=${encodeURIComponent(paramValue)}`;
console.log(safeUrl);
// Output: "https://api.sylvaera.com/v1/items?filter=status%3Dactive%26type%3Dprod%2Ftest"
Strict Percent-Encoding for OAuth and APIs
Standard encodeURIComponent() does not encode characters like !, ', (, ), and * because they are unreserved in older standards. However, modern authentication protocols (such as OAuth 1.0a and AWS SigV4) require strict percent-encoding where all special characters are escaped:
function strictUrlEncode(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
const strictResult = strictUrlEncode("user(admin)*");
console.log(strictResult); // "user%28admin%29%2A"
Encode URLs and Query Parameters Online
Need to build safe API URLs, webhook callback parameters, or query strings without manual string manipulation? Use Sylvaera's URL Encoder. It offers standard and strict encoding modes directly in your browser with complete privacy.