How to Encode URL in JavaScript?

You can use the built-in method encodeURIComponent() to encode a URL in JavaScript.

const url = 'http://www.google.com/search?q='; const queryString = '@Tom & #Jerry' const encUrl = url + encodeURIComponent(queryString); // Output: http://www.google.com/search?q=%40Tom%20%26%20%23Jerry

URL Encoding

A URL (Uniform Resource Locator) is a specific web address that helps locate resources on the internet, such as web pages, images, or files. URL encoding is a mechanism used to convert data into a secure and valid format that can be safely transmitted over the internet. By encoding special characters and non-ASCII characters, the reliability, security, and consistency of URLs are enhanced, preventing issues like data corruption, incorrect interpretation, or vulnerabilities.

Why do you need to encode?

How to encode URL parameters in javascript

In URLs, characters are classified as reserved or unreserved. Reserved characters, such as ?, /, #, and :, have special meanings within URLs and must be used correctly. Unreserved characters have no special meaning, but characters outside the standard ASCII set must be URL-encoded using the "%" symbol followed by a two-character hexadecimal value corresponding to their UTF-8 representation. This encoding ensures proper transmission and interpretation of characters in URLs.

https://www.example.com //normal URL
https%3A%2F%2Fwww.example.com //encoded URL

JavaScript URL Encode

To encode URLs in JavaScript, you have two main functions: encodeURI() and encodeURIComponent(). These functions replace specific characters in a URL with up to four escape sequences that represent the UTF-8 encoding of each character. The distinction between these functions lies in their encoding scope – encodeURI() is used for entire URLs, while encodeURIComponent() is designed for individual URL components, ensuring proper encoding and compliance with URL standards.

encodeURI()

The encodeURI() method is designed to encode entire URLs. It expects a full URL as input and encodes characters that require encoding, excluding reserved characters like ~!$&@#*()=:/,;?+. This method ensures that the URL structure remains intact while properly encoding characters that might cause issues.

encodeURI( complete_uri_string )
Example
const url = 'http://example.com/$some # thing here@/'; const encodedUrl = encodeURI(url); // output: http://example.com/$some%20#%20thing%20here@/
run this source code Browser View

JavaScript encodedUrl()

Full Source | JavaScript
<!DOCTYPE html> <html> <body> <h2>JavaScript encodedUrl()</h2> <p id="demo"></p> <script> const url = 'http://example.com/$some # thing here@/'; // encode complete URL const encodedUrl = encodeURI(url); // print encoded URL document.getElementById("demo").innerHTML = encodedUrl; // output: http://example.com/$some%20#%20thing%20here@/ </script> </body> </html>

encodeURIComponent()

The encodeURIComponent() function is a built-in method used specifically to encode individual URL components, such as query string parameters. It employs the UTF-8 encoding scheme to encode all characters with special meanings in URLs, except for -_.!~*'(). This function is suitable for ensuring correct encoding of specific components within a URL, like query parameters.

encodeURIComponent( uri_string_component )

Ideally, you should use the encodeURIComponent() method only for encoding query string parameters or path segments.

Example
const url = 'http://www.google.com/search?q='; const queryString = '@Tom & #Jerry' const encUrl = url + encodeURIComponent(queryString); // Output: http://www.google.com/search?q=%40Tom%20%26%20%23Jerry
run this source code Browser View

JavaScript Encode URL Parameters

Full Source | JavaScript
<!DOCTYPE html> <html> <body> <h2>JavaScript Encode URL Parameters</h2> <p id="demo"></p> <script> const url = 'http://www.google.com/search?q='; const queryString = '@Tom & #Jerry' // build full URL const encUrl = url + encodeURIComponent(queryString); // print full URL document.getElementById("demo").innerHTML = encUrl; // Output: http://www.google.com/search?q=%40Tom%20%26%20%23Jerry </script> </body> </html>

The encodeURI() function is used to encode entire URLs, whereas encodeURIComponent() is employed to encode single URL parameter values. This distinction ensures that the appropriate level of encoding is applied based on whether you're dealing with a complete URL or just a specific parameter value within it.

URLSearchParams

An object that implements the URLSearchParams interface can be conveniently utilized within a for...of loop to iterate through key/value pairs. This allows you to traverse the pairs in the exact order they appear in the query string. This approach is supported across all modern browsers. It can be used like this:

Example
const params = new URLSearchParams({ var1: "value1", var2: "value2", arr: "foo", }); console.log(params.toString()); //Output: var1=value1&var2=value2&arr=foo
run this source code Browser View

JavaScript URLSearchParams

Full Source | JavaScript
<!DOCTYPE html> <html> <body> <h2>JavaScript URLSearchParams</h2> <p id="demo"></p> <script> const params = new URLSearchParams({ var1: "value1", var2: "value2", arr: "foo", }); document.getElementById("demo").innerHTML = params.toString(); </script> </body> </html>

Conclusion

To encode URLs in JavaScript, two primary functions are utilized: encodeURI() for full URLs and encodeURIComponent() for individual URL components like query parameters. The former maintains the overall URL structure while excluding reserved characters, while the latter encodes all special characters except -_.!~*'(). These functions ensure proper URL encoding and are vital for handling various aspects of web addresses.