You can use the encodeURIComponent() and encodeURI() functions in JavaScript to encode a URL.

encodeURIComponent() function is used to encode individual components of a URI (Uniform Resource Identifier), such as the path, query string, and fragment identifier. It encodes all characters except for the following:

  • alphabetic characters
  • decimal digits
  • the following special characters: – _ . ! ~ * ‘ ( )

For example:

let url = "https://example.com/search?q=hello world";
let encoded = encodeURIComponent(url);
console.log(encoded); // "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dhello%20world"

encodeURI() function is used to encode the entire URI, including the scheme, authority, path, query string, and fragment identifier. It encodes all characters except for the following:

  • alphabetic characters
  • decimal digits
  • the following special characters: – _ . ! ~ * ( ) ‘
  • the following reserved characters: ; / ? : @ & = + $ , #

For example:

let url = "https://example.com/search?q=hello world";
let encoded = encodeURI(url);
console.log(encoded); // "https://example.com/search?q=hello%20world"

In general, you should use encodeURIComponent() when encoding individual components of a URI and encodeURI() when encoding the entire URI.

It’s also worth noting that there are corresponding decodeURIComponent() and decodeURI() functions which are used to decode the encoded URI/URIComponent.

Also Read:

Categorized in: