encodeURIComponent & encodeURI in JavaScript

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:

foo://example.com:8042/user?name=john#about

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        
Courtesy:

There are two types of URI:

  1. URL (Uniform Resource Locator)
  2. URN (Uniform Resouce Name)

With that, short intro I will dive into the function usages.

  • encodeURIComponent: The word itself is self-explanatory. This is used to encode a single component of a URI, such as query parameters or fragments.It escapes all characters except the following: alphabetic characters, decimal digits, - _ . ! ~ * ' ( )It escapes characters that have special meanings in a URL, like ? and &.Use encodeURIComponent when you need to encode a specific component of a URI.

const param = "[email protected]";
const encodedParam = encodeURIComponent(param);
console.log(encodedParam); // "example%40domain.com"        

Example:

hello=world?youknow     -> hello%3Dworld%3Fyouknow%3D%3D        

  • encodeURI: Used to encode an entire URI, including the scheme, authority, path, query, and fragment components.It escapes fewer characters than encodeURIComponent. It doesn't escape characters that have a special meaning in a URI, such as ? and &.So, when you are encoding keep in mind these ? and &are having special meanings in a URI. So, if you have a query like

?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.

要查看或添加评论,请登录

Parathan Thiyagalingam的更多文章

社区洞察

其他会员也浏览了