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