Encode URL Parameters using encodeURIComponent()
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);
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);
Read more about how to use URL parameters with the URLSearchParams() interface.
Encode a Full URL Using encodeURI()
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);