encodeURIComponent & encodeURI in JavaScript
encodeURIComponent and encodeURI are two JS functions used for encoding components of a URI (Uniform Resource Identifier). The encoding will safeguard against adding a suspicious or any character that makes an invalid URL (Uniform Resouce Locator).
The URI is a sequence of characters that distinguish one character from others.
For example, let's see this URI:
This URI contains a scheme name, authority, path, query, and fragment. A URI does not need to contain all these components. All it needs is a scheme name and a file path, which can be empty.
Here:
Schema Name -> foo
Authority -> example.com:8042
Path -> /user
Query -> ?name=john
Fragment -> about
There are two types of URI:
With that, short intro I will dive into the function usages.
领英推荐
const param = "[email protected]";
const encodedParam = encodeURIComponent(param);
console.log(encodedParam); // "example%40domain.com"
Example:
hello=world?youknow -> hello%3Dworld%3Fyouknow%3D%3D
?query=477f+dsjfn?678&olm
Since these ? and & are placed in the query part when handling this URI, This would become invalid.
Use encodeURI when you need to encode a complete URI.
const uri = "https://www.example.com/path?param=example&query=test";
const encodedURI = encodeURI(uri);
console.log(encodedURI);
// "https://www.example.com/path?param=example&query=test"
Keep in mind when encoding a URI, If we need to encode the URI components more specifically handle the URI meaningful character then should use encodeURIComponent. Otherwise, if we need to encode the whole URL, then we should use encodeURI.
Hope this was clear to you.
Any comments are welcomed. Thanks for reading.