encode url in js
encode url in js is percent-encoding: a character that would change the shape of a URL is written as % plus the hex of its UTF-8 bytes. The two functions are encodeURI and encodeURIComponent. encodeURI is for a complete URL that already has its /, ?, and & in the right places. encodeURIComponent is for one piece you are about to insert, such as a query value.
const full = "https://example.com/my file?q=a b";
const value = "Ben & Jerry's";
const encodedUrl = encodeURI(full);
const encodedValue = encodeURIComponent(value);
encodedUrl is https://example.com/my%20file?q=a%20b. Each space becomes %20. ://, /, ?, and = stay, so the result still has a path and a query. encodedValue is Ben%20%26%20Jerry's. The space is %20, & is %26, and the apostrophe stays.
Both functions encode with UTF-8, one %XX per byte. é is %C3%A9. 文 is %E6%96%87. The emoji 😀 is one character made of two UTF-16 code units, and it becomes four sequences, %F0%9F%98%80. Hex digits come out uppercase.
The characters both functions leave as they are are A–Z, a–z, 0–9, and - _ . ! ~ * ' ( ). encodeURI also leaves ; / ? : @ & = + $ , #, the characters that mark parts of a URL. encodeURIComponent encodes that second set. [ and ] are outside both safe lists, so both functions turn them into %5B and %5D.
A value that is not a string is turned into a string first. encodeURIComponent(42) is "42". encodeURIComponent(null) is "null". encodeURIComponent(undefined) is "undefined". An object becomes the string "[object Object]", and encodeURIComponent({}) is %5Bobject%20Object%5D.
Query values
encodeURI on a URL you built by concatenation leaves &, =, and # inside the value. The parser then splits the query in the wrong place.
const name = "Ben & Jerry's";
const bad = encodeURI(`https://example.com/?choice=${name}`);
const good = `https://example.com/?choice=${encodeURIComponent(name)}`;
bad is https://example.com/?choice=Ben%20&%20Jerry's. new URL(bad).searchParams is the pairs ["choice", "Ben "] and [" Jerry's", ""]. The raw & is still a separator. good is https://example.com/?choice=Ben%20%26%20Jerry's. Its search params are the one pair ["choice", "Ben & Jerry's"].
With more than one field, encode each key and each value, then join the pairs with &.
const q = "a&b";
const page = "1";
const href =
"https://example.com/search?q=" +
encodeURIComponent(q) +
"&page=" +
encodeURIComponent(page);
href is https://example.com/search?q=a%26b&page=1. The & between q and page is the separator you wrote. The & inside q is %26.
URLSearchParams
URLSearchParams encodes keys and values when you serialize the query. You pass the raw strings.
const params = new URLSearchParams();
params.append("choice", "Ben & Jerry's");
params.append("q", "a b");
const href = "https://example.com/search?" + params.toString();
params.toString() is choice=Ben+%26+Jerry%27s&q=a+b, and that is the query in href. A space is +. & is %26. The apostrophe is %27. params.get("choice") returns Ben & Jerry's, the decoded value. append and get use the unencoded text. If you append a key that is already percent-encoded, that text is encoded again: append("%24%26", "value") serializes as %2524%2526=value.
This is the application/x-www-form-urlencoded encoding. The set it percent-encodes is everything except ASCII letters, digits, *, -, ., and _, and a space is +. So !, ', (, ), and ~ are encoded, and * is not. encodeURIComponent does the opposite with those five punctuation marks, and it writes a space as %20. Replacing %20 with + after encodeURIComponent fixes the space and still leaves the apostrophe alone. For a form body, URLSearchParams is the call that applies the form set.
The constructor reads + as a space, and it does not parse a full URL. new URLSearchParams("bin=E+AXQB+A").get("bin") is "E AXQB A". Building the same pair with append("bin", "E+AXQB+A") keeps the plus signs, and toString() is bin=E%2BAXQB%2BA.
new URL() parses an absolute URL and percent-encodes characters that cannot appear raw. It has been on the global object in Node.js since 10.0.0, and URLSearchParams has been global for the same release.
const url = new URL("https://example.com/my file");
url.searchParams.set("q", "Ben & Jerry's");
After the constructor, the path space is already %20. After set, url.href is https://example.com/my%20file?q=Ben+%26+Jerry%27s. Writing searchParams replaces the query with the URLSearchParams serialization, so the space in the value is +.
A non-ASCII host goes through Punycode inside URL. new URL("https://例子.测试/path").hostname is xn--fsqu00a.xn--0zwm56d. encodeURI("https://例子.测试/path") percent-encodes those characters in place and returns https://%E4%BE%8B%E5%AD%90.%E6%B5%8B%E8%AF%95/path.
encodeURI and encodeURIComponent are language globals, so Node.js has them too. node:querystring is a separate module. Its docs mark it Stability 2, Stable, and point at URLSearchParams when the same code should run in the browser. querystring.stringify({ choice: "Ben & Jerry's" }) returns choice=Ben%20%26%20Jerry's: the space is %20, and the apostrophe stays. The legacy API in node:url is url.parse. That one is Stability 3, Legacy, and the docs tell you to use the WHATWG URL class.
RFC 3986
RFC 3986 calls letters, digits, -, ., _, and ~ unreserved. It also reserves !, ', (, ), and *, even though those five are not used as delimiters. encodeURIComponent leaves all five unencoded, along with ~. Square brackets are reserved for an IPv6 host. encodeURI still percent-encodes them.
The component helper on the MDN page for encodeURIComponent encodes the five reserved marks and forces the hex to uppercase:
function encodeRFC3986URIComponent(str) {
return encodeURIComponent(str).replace(
/[!'()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
encodeRFC3986URIComponent("!'()*") is %21%27%28%29%2A. encodeRFC3986URIComponent("Ben & Jerry's") is Ben%20%26%20Jerry%27s.
OAuth 1.0 uses that set when it builds the signature base string and the Authorization header. Characters outside letters, digits, -, ., _, and ~ must be encoded, the hex digits must be uppercase, and a space is %20.
Lone surrogates
A JavaScript string is UTF-16. A code unit from U+D800 through U+DFFF is a surrogate. A high surrogate followed by a low surrogate is one character. One leftover unit is a lone surrogate, and it is not a Unicode character, so it has no UTF-8 encoding. encodeURI and encodeURIComponent throw URIError. In Node.js the message is URI malformed.
encodeURI("\uD800\uDFFF");
encodeURI("\uD800");
The pair encodes as %F0%90%8F%BF. The lone \uD800 throws.
String.prototype.isWellFormed() reports whether any lone surrogate is present. "\uD800".isWellFormed() is false. "\uD800\uDFFF".isWellFormed() is true. toWellFormed() replaces each lone surrogate with U+FFFD, and encodeURI("\uD800".toWellFormed()) is %EF%BF%BD. Both methods shipped in browsers in October 2023 and in Node.js 20.0.0. A try/catch around the encode call is the other way to handle the URIError.
Decoding
decodeURI turns %XX sequences back into characters, and it leaves sequences for ; / ? : @ & = + $ , # in the output.
const encoded =
"https://example.com/docs/JavaScript%3A%20a_scripting_language";
const asUrl = decodeURI(encoded);
const asValue = decodeURIComponent(encoded);
asUrl is https://example.com/docs/JavaScript%3A a_scripting_language. %20 becomes a space. %3A stays, because encodeURI would not have encoded :. asValue is https://example.com/docs/JavaScript: a_scripting_language. decodeURIComponent decodes every sequence, including the ones encodeURIComponent does not produce.
Both decoders throw URIError when % is not followed by two hex digits, or when the bytes are not valid UTF-8. decodeURI("%E0%A4%A") throws. In Node.js that message is URI malformed as well.
A form query uses + for a space. decodeURIComponent leaves + as a plus sign. Replace + with a space first:
function decodeQueryParam(p) {
return decodeURIComponent(p.replace(/\+/g, " "));
}
decodeQueryParam("search+query%20%28correct%29") is search query (correct).
Encoding twice
encodeURIComponent("a b") is a%20b. Passing that result through encodeURIComponent again produces a%2520b, because % encodes as %25. decodeURIComponent("a%2520b") is a%20b. One more decode returns a b. RFC 3986 says an implementation must not percent-encode or decode the same string more than once. An already encoded value has to be decoded back to the raw text before you encode it for a new URL.
encodeURIComponent on a whole URL encodes the structure along with the data. encodeURIComponent("https://example.com/a?b=c") is https%3A%2F%2Fexample.com%2Fa%3Fb%3Dc.
What each call encodes
For a finished URL string, use encodeURI. For a key or a value you are inserting, use encodeURIComponent. For a query you are building from fields, use URLSearchParams. For an OAuth 1.0 signature base string, or any other client that requires the RFC 3986 set, encode the five marks encodeURIComponent keeps.
| Character | encodeURI | encodeURIComponent | URLSearchParams |
|---|---|---|---|
| space | %20 | %20 | + |
& | & | %26 | %26 |
= | = | %3D | %3D |
? | ? | %3F | %3F |
# | # | %23 | %23 |
/ | / | %2F | %2F |
' | ' | ' | %27 |
* | * | * | * |
~ | ~ | ~ | %7E |
[ | %5B | %5B | %5B |
encodeURI and encodeURIComponent have been in browsers since July 2015. URLSearchParams has been in browsers since April 2018, and the URL constructor is widely available as of April 2021. Node.js has had both classes on the global object since 10.0.0.