How to encode a url with javascript

Learn how to encode a URL with javascript.

We often need to encode the URL if we want to send it as a part of the get request.

"https%3A%2F%2Flearnersbucket.com%2Fa%20file%20with%20spaces.html"

How do we encode URL in javascript?.

Based on our need there are two different methods available in javascript for encoding a URL.

encodeURI()

This method is used to encode a full URL. But it does not encode the following characters ~!@#$&*()=:/,;?+.

encodeURI("https://learnersbucket.com/ hello !/")
// "https://learnersbucket.com/%20hello%20!/"

encodeURIComponent()

This method is meant to encode a single URL parameter value. It also does not encode some characters like -_.!~*'().

As it deos encode the / character we cannot use it to encode the whole URL.

encodeURIComponent("https://learnersbucket.com/a file with spaces.html")
// "https%3A%2F%2Flearnersbucket.com%2Fa%20file%20with%20spaces.html"

There is a oppossite method available to decode the component decodeURI() and decodeURIComponent() which can be used on server side like in Node.js.