Lesson 3

encodeURI vs encodeURIComponent

JavaScript helpers and when each applies to paths vs query values.

JavaScript exposes two global functions with nearly identical names but different sets of characters they leave unescaped. Both target URI text, but they assume different scopes of data.

encodeURIComponent encodes “a single component”

Use it for query values, path segments, fragment identifiers, and any string that must not inject structure:

encodeURIComponent("a/b?c=1&d=2");
// "a%2Fb%3Fc%3D1%26d%3D2"

Notice /, ?, &, = all become percent escapes so the value remains opaque when embedded.

Typical pattern when building a query string manually:

const q = new URLSearchParams({
  title: "Q&A / Notes",
  next: "https://example.com/a?x=1",
});
q.toString(); // title=Q%26A+%2F+Notes&next=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1
// (Note: URLSearchParams uses application/x-www-form-urlencoded rules; + for space)

For hand-wired strings, prefer URLSearchParams or libraries that already handle separator characters.

encodeURI preserves URI delimiters

encodeURI assumes you pass an almost complete URI and only need to fix characters that are illegal globally while keeping structural punctuation meaningful:

encodeURI("https://example.com/résumé?id=1#top");
// https://example.com/r%C3%A9sum%C3%A9?id=1#top

It does not encode characters such as ?, #, / when they appear—because it believes they might be real delimiters. That is dangerous if your “data” includes those symbols.

encodeURI("https://example.com/search?q=a/b");
// leaves the slash—may break server expectations if / was data, not a path separator

Rule of thumb: do not use encodeURI to protect arbitrary user text; use encodeURIComponent (or higher-level APIs) per component.

Quick decision guide

SituationPreferred helper
Single path segment containing / as dataencodeURIComponent each segment
Full URL string from user with unknown delimitersParse with URL, then encode each part
Entire URI already structurally sound, only accents failPossibly encodeURI—often still clearer to normalise hosts/paths separately
Repeated building of APIsPrefer URL + URLSearchParams, not concatenation

decodeURI vs decodeURIComponent

Symmetrical cautions apply:

decodeURIComponent("100%2525"); // may yield "100%25" if only one decoding pass—but mind double-encoding bugs upstream
decodeURI("http://host/%7Euser") → keeps delimiters untouched while decoding escapes in other positions

If you mismatch encode/decode scopes, decoded text can re-introduce separators (&, ?) that change how parameters parse—classic open-redirect or filter-bypass pitfalls when reflected into HTML or headers.

When you want to practice, use the related DevCove tool — optional, not part of this lesson.

Open related tool

Back to course overview