URL encoding, also known as percent-encoding, is a process of encoding special characters in a URL to make the transmitted data more secure and reliable. It helps avoid cross-site attacks while calling a remote web service.

There can be two types of characters in a URL: reserved and unreserved. The reserved characters are those characters that have special meaning within a URL. For example, ?, /, #, :, etc. are reserved characters, and they must not be a part of query strings or path segments. Unreserved characters have no special meaning. Using URL encoding, these characters are converted to special character sequences.

In this article, you'll learn how to encode a URL using JavaScript built-in functions. JavaScript provides two functions to help you encode a URL: encodeURI() and encodeURIComponent(). Both of these methods are intended to be used for different use cases. Let us start with the first.

encodeURI()

The encodeURI() method is meant to encode a complete URL. It assumes that the input is a full URL with some special characters that need encoding in it. Therefore, it doesn't encode the reserved characters (~!$&@#*()=:/,;?+).

Let us look at an example:

const url = 'http://example.com/!leearn javascript$/';

// encode complete URL
const encodedUrl = encodeURI(url);

// print encoded URL
console.log(encodedUrl);

// output: http://example.com/!leearn%20javascript$/

encodeURIComponent()

The encodeURIComponent function should be used to encode a single URL component (like query string parameter) instead of the complete URL. It uses the UTF-8 encoding scheme and encodes all characters with special meaning except -_.!~*'().

If you use encodeURIComponent() to encode a full URL, everything including path separators (/) will be encoded as shown below:

const url = 'http://example.com/!leearn javascript$/';

// encode complete URL
const encodedUrl = encodeURIComponent(url);

// print encoded URL
console.log(encodedUrl);

// output: http%3A%2F%2Fexample.com%2F!leearn%20javascript%24%2F

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

const baseUrl = 'http://www.google.com/searc?q=';
const query = 'Nodejs & JavaScript'

// encode query string
const encodedQuery = encodeURIComponent(query);

// build full URL
const url = baseUrl + encodedQuery;

// print full URL
console.log(url);

// output
// http://www.google.com/searc?q=Nodejs%20%26%20JavaScript

You should call the encodeURIComponent() method for every single query string parameter, which might include special characters to avoid network errors and unexpected response.

Note: MDN suggests an improvement to adhere the RFC 3986 standard (which reserves !, ', (, ), and * characters) by implementing the following method:

const fixedEncodeURIComponent = (str) => {
    return encodeURIComponent(str).replace(/[!'()*]/g, (c) => {
        return '%' + c.charCodeAt(0).toString(16);
    });
}

console.log(fixedEncodeURIComponent('node * ! javascript'));

// output: node%20%2a%20%21%20javascript

Read Next: How to decode a URL using JavaScript

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5).