How to Use the decodeURI() Function in JavaScript

09/30/2021

Contents

In this article, you will learn how to use the decodeURI() function in JavaScript.

Using the decodeURI() Function in JavaScript

In JavaScript, the decodeURI() function is used to decode a Uniform Resource Identifier (URI) that has been encoded using the encodeURIComponent() function. This function is useful for working with URLs that contain special characters or non-ASCII characters, as it can convert these characters into their original form.

Here are the basic steps to use the decodeURI() function in JavaScript:

Encode the URI

Before you can use the decodeURI() function to decode a URI, you must first encode it using the encodeURIComponent() function. This function takes a string as its input and returns a new string that is encoded for use in a URL.

For example, if you have a URL that contains a special character like a space, you would need to encode it before passing it to the decodeURI() function. Here is an example of how to encode a URL using the encodeURIComponent() function:

const myUrl = 'https://example.com/search?q=javascript basics';
const encodedUrl = encodeURIComponent(myUrl);

Decode the URI

Once you have encoded the URI using the encodeURIComponent() function, you can decode it using the decodeURI() function. This function takes a string as its input and returns a new string that is decoded from its encoded form.

Here is an example of how to use the decodeURI() function to decode an encoded URL:

const encodedUrl = 'https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Djavascript%20basics';
const decodedUrl = decodeURI(encodedUrl);

Use the Decoded URI

Once you have decoded the URI using the decodeURI() function, you can use it in your JavaScript code as needed. For example, you might use the decoded URL to make an AJAX request or to navigate to a new page.

Here is an example of how to use the decoded URL to make an AJAX request:

const xhr = new XMLHttpRequest();
xhr.open('GET', decodedUrl);
xhr.onload = function() {
  // Handle the response
};
xhr.send();

And that’s how you can use the decodeURI() function in JavaScript to decode an encoded URI. Remember to always encode your URLs before passing them to the decodeURI() function to ensure that any special or non-ASCII characters are properly decoded.