A URL can be encoded using the encodeURI() function. This function takes a parameter that is a URL string and returns an encoded version of that string. URL can be decoded using the decodeURI() method. This function requires an encoded URL string as a parameter and returns that decoded string.

Making a GET request to an API with query parameters often involves encoding and decoding URIs and URI components. It is common practice to generate a URL string with query parameters, and the response server must decode this URL in order to understand it. The URL is automatically encoded by browsers, meaning that some special characters are changed to other reserved characters before the request is sent. For instance, the space character " " is transformed to either + or 20%.

encodeURI function - The full URI is encoded using the encodeURI() function. With the exception of (, /?: @ & = + $ #) characters, this function encodes special characters.

encodeURI( complete_uri_string )
<script>
const url = "https://www.google.com/search?q=code solution stuff";
const encodedURL = encodeURI(url);
document.write(encodedURL)
</script>

Output

https://www.google.com/search?q=code%20solution%20stuff

Note : - Use encodeURIComponent if you wish to encrypt characters like /?: @ & = + $ #. ().

 decodeURI function - The URI created by encodeURI is decoded using the decodeURI() method ().

decodeURI( complete_encoded_uri_string )
<script>
const url = "https://www.google.com/search?q=code%20solution%20stuff";
const decodedURL = decodeURI(url);
document.write(decodedURL)
</script>

Output

https://www.google.com/search?q=code solution stuff

Recommended Posts

View All

What is the purpose of the array slice method


The array slice method is a powerful tool in JavaScript used to extract a section of an array and return a new array. In this article, you'll learn ab...

What is the difference between Call, Apply and Bind


Looking to learn about the differences between Call, Apply, and Bind in JavaScript? This article breaks down the nuances of each method and provides c...

JavaScript Program to Create Objects in Different Ways


Learn different ways to create objects using JavaScript with our step-by-step guide. From object literals to constructor functions and classes, this p...

Difference between var and let in JavaScript


Learn the difference between var and let in JavaScript. Understand variable hoisting, scope, and how they affect your code's behavior. Get started now...

Describe Singleton Pattern In JavaScript


The singleton pattern is a popular design pattern one for JavaScript. It offers a means of organizing the code into a logical chunk that can be reache...