How to Encode JavaScript URL

URL encoding mechanism is used for encoding any data in URLs to a secure format that can be transmitted over the internet.

Encoding a JavaScript URL can be done with two JavaScript functions depending on what you are going to do. These functions are: encodeURI() and encodeURIComponent() . Both are used to encode a URI by replacing each instance of certain characters by up to four escape sequences representing the UTF-8 encoding of the character. Let’s discuss each of them and point their peculiarities for encoding a URL. You can also check our URL Encoder tool to make your work much easier.

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 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

Do not use escape() function which is deprecated, and does not encode "+" characters, which will be interpreted as encoded spaces on the server.

The encodeURIComponent() Function

The other built-in method encodeURIComponent() is also used to encode a URL in JavaScript. It will return a new string representing the given string encoded as a URI component. The function encodes all the characters except the following ones:

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);
Do you find this helpful?

Related articles