W3docs

How to Encode JavaScript URL

In the tutorial, you can read and learn useful information about the two JavaScript functions that are used for encoding URL and their use cases in detail.

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: <kbd class="highlighted">encodeURI()</kbd> and <kbd class="highlighted">encodeURIComponent()</kbd>. 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 <kbd class="highlighted">encodeURI()</kbd> 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 ; , / ? : @ & = + $ - \_ . ! ~ \* ' ( ) #

Danger

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 <kbd class="highlighted">encodeURIComponent()</kbd> 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:

<kbd class="highlighted">A-Z a-z 0-9 - _ . ! ~ * ' ( )</kbd>

The difference between two functions is that the <kbd class="highlighted">encodeURI()</kbd> encodes a full URL and <kbd class="highlighted">encodeURIComponent()</kbd> encodes a single URL parameter value.

The following examples show the difference between these two functions:

How to Encode JavaScript URL

javascript— editable

How to Encode JavaScript URL

javascript— editable