JavaScript Interview Question #141

What is the difference between encodeURIComponent() and encodeURI()?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

encodeURI is intended for encoding a complete URI while preserving characters that have structural meaning in a URI. encodeURIComponent is intended for encoding an individual URI component such as a query-string value and therefore escapes more characters.

Detailed Explanation

encodeURI is intended for encoding a complete URI while preserving characters that have structural meaning in a URI. encodeURIComponent is intended for encoding an individual URI component such as a query-string value and therefore escapes more characters.

When inserting arbitrary user data into a query parameter, encodeURIComponent is normally the appropriate choice. The URL and URLSearchParams APIs are often clearer for constructing modern URLs.

Code Example

const search = "C# & JavaScript";

const url =
    "/search?q=" + encodeURIComponent(search);

console.log(url);
// /search?q=C%23%20%26%20JavaScript