How to Encode URL's in JavaScript

Only ASCII characters can be sent across the internet, which is why special characters in URL's have to be encoded before a request is made to a server. There are times when a URL containing parameters needs to be encoded in a JavaScript program before it is put into an HTTP GET request, which is what we will be looking at in this article.

 

Encode URL Parameters using encodeURIComponent()

The encodeURIComponent() method should be used to encode the values of URL parameters only. If you supply a full URL it will return a none working URL. In the example below, we will get the parameter search from the current URL and encode its value before adding it back to the base of the URL.

 

var uri = window.location.search;
console.log(uri);
?search=eggs$bacon
var paramters = new URLSearchParams(uri);

var search_param = paramters.get('search');

var encoded_param = encodeURIComponent(search_param);

var url = 'https://www.example.com/?search=' + encoded_param

console.log(url);
https://www.example.com/?search=eggs%24bacon

 

Read more about how to use URL parameters with the URLSearchParams() interface.

 

Encode a Full URL Using encodeURI()

The encodeURI() method can encode URL parameters while maintaining a working URL in the encoded output. As a result, it might miss some characters that should be encoded that encodeURIComponent() would encode.

 

var full_url = window.location.href;

var encoded_url = encodeURI(full_url);

console.log(encoded_url);
https://www.example.com/?search=eggs$bacon

 

Conclusion

You now know how to encode URL's in JavaScript and which method should be used over another depending on what characters you need to encode.

url encode