URL encoding mechanism is used for encoding any data in URLs to a secure format that can be transmitted over the internet.
The encodeURI() Function¶
The encodeURI() function will return a new string representing the given string encoded as a URI. It encodes all the characters except the following ones:
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
The encodeURIComponent() Function¶
A-Z a-z 0-9 - _ . ! ~ * ' ( )
The difference between two functions is that the encodeURI() encodes a full URL and encodeURIComponent() encodes a single URL parameter value.
The following examples shows the difference between these two functions:
let encURI = encodeURI("http://w3docs.com/ welcome!/"); //"http://w3docs.com/%20welcome!/" console.log(encURI);
let encURIComp = encodeURIComponent("http://www.example.org/a file with spaces.html"); // "http%3A%2F%2Fw3docs.com%2F%20welcome!%2F"console.log(encUrl); console.log(encURIComp);