JavaScript encodeURI vs. encodeURIComponent: Encode URLs correctly
encodeURI() preserves delimiters used in a URL’s structure. encodeURIComponent() encodes a component value such as a search term. For query parameters, pass raw values to URLSearchParams. Decode at the corresponding layer and handle malformed percent escapes.
What the four functions handle
A URI (Uniform Resource Identifier) identifies a resource. A URL locates one. Percent encoding represents bytes as %HH, so a non-ASCII character can produce several UTF-8 byte escapes. This does not encrypt the data. encodeURIComponent() leaves ASCII letters, digits and characters such as - _ . ! ~ * ' ( ) unchanged but encodes more delimiters than encodeURI().
| Function | Use case | What happens to delimiters |
|---|---|---|
encodeURI() |
A complete URI | Preserves structural delimiters such as :, /, ?, &, =, # |
encodeURIComponent() |
A path segment or query value | Encodes those delimiters as data |
decodeURI() |
Decode a complete URI | Keeps certain encoded reserved delimiters |
decodeURIComponent() |
Decode an individual value | Decodes percent escapes, including delimiters |
encodeURI("a&b=c"); // "a&b=c"
encodeURIComponent("a&b=c"); // "a%26b%3Dc"
decodeURI("%26"); // "%26"
decodeURIComponent("%26"); // "&"
Build a search URL in a complete example
Save the complete code as url-encoding.html in UTF-8 and open it. It builds and inspects the URL without making a request. Parameter s contains the search term.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Encode and decode URL values</title>
</head>
<body>
<h1>Put a search term in a URL</h1>
<label for="keyword">Search term</label>
<input id="keyword" value="C++ & Café">
<button id="encode" type="button">Encode</button>
<button id="restore" type="button">Restore defaults</button>
<pre id="output"></pre>
<label for="encoded">Encoded value</label>
<input id="encoded" value="Caf%C3%A9">
<button id="decode" type="button">Decode</button>
<pre id="decoded"></pre>
<script>
const keyword = document.getElementById("keyword");
const output = document.getElementById("output");
function encode() {
try {
const value = keyword.value;
const component = encodeURIComponent(value);
const url = new URL("https://www.codingfactory.net/");
url.searchParams.set("s", value);
output.textContent = [
`encodeURI: ${encodeURI(value)}`,
`encodeURIComponent: ${component}`,
`Decoded again: ${decodeURIComponent(component)}`,
`Search URL: ${url.href}`,
`Value from URL: ${url.searchParams.get("s")}`
].join("\n");
} catch (error) {
output.textContent = error.name;
}
}
document.getElementById("encode").addEventListener("click", encode);
document.getElementById("restore").addEventListener("click", () => {
keyword.value = "C++ & Café";
encode();
});
document.getElementById("decode").addEventListener("click", () => {
try {
document.getElementById("decoded").textContent =
decodeURIComponent(document.getElementById("encoded").value);
} catch (error) {
document.getElementById("decoded").textContent = error.name;
}
});
encode();
</script>
</body>
</html>
The sample’s + and & remain with encodeURI() but become %2B and %26 with encodeURIComponent(). If the value goes after ?s=, an unescaped ampersand could start a new parameter. URLSearchParams serializes a space as + and a literal plus as %2B. Compare the recovered value with C++ & Café. Try a&b=1 and restore. Pass the raw value to set() to avoid double encoding.
Distinguish decoding errors from double encoding
The decode field initially gives Café. Change it to % or %E0%A4%A to get URIError. An isolated UTF-16 surrogate can also fail during encoding. The demo prints the error name because descriptions vary by browser. See URIError.
const once = encodeURIComponent("&"); // "%26"
const twice = encodeURIComponent(once); // "%2526"
decodeURIComponent(twice); // "%26": decodes one layer only
decodeURIComponent("a+b"); // "a+b": does not turn a plus into a space
Decode once for the layer you are reading. A value from URLSearchParams.get() is already decoded. Decoding again simply because a percent sign remains can change the original data. decodeURIComponent() leaves a plain plus alone, while parsing a query with URLSearchParams treats it as a space.
Validate the URL destination separately
Encoding does not validate the destination of a URL. If external input chooses where to navigate, validate the protocol and host separately. Use textContent when displaying the strings to prevent markup parsing.
Build a path segment and query value together
Run the snippet in the browser Console. Encode just the item name so its slash belongs to one path segment. Pass the original category to searchParams.set(). No request is sent.
{
const item = "Part A/B";
const category = "Café + tea";
const url = new URL("https://example.com/");
url.pathname = "/items/" + encodeURIComponent(item);
url.searchParams.set("category", category);
console.log(url.href);
console.log(decodeURIComponent(url.pathname.split("/").at(-1)));
console.log(url.searchParams.get("category"));
}
The URL is https://example.com/items/Part%20A%2FB?category=Caf%C3%A9+%2B+tea. The next lines show Part A/B and Café + tea. Split the path before decoding the segment. Dot segments . and .. are normalized by URL parsing. If an application’s server or router handles encoded slashes differently, consider passing the identifier in the query.




