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

4 Ways to Empty an Array in JavaScript


It is possible to empty an array in a few different ways, so let's go over every method that is available.

Difference between Function, Method and Constructor calls in JavaScript


You are probably used to thinking about functions, methods, and class constructors as three distinct things if you are experienced with object-oriente...

JavaScript's Lambda and Arrow Functions


Lambda and arrow functions in JavaScript allow for concise and elegant code. Learn how to use them to streamline your code and improve readability.

JavaScript Program to Check if An Object is An Array


The function toString method?from Object.prototype is the best approach to determine whether an object is an instance of a given class or not.

What is JSON? Know how it Works with Examples


Learn what JSON is and how it works with examples in this comprehensive guide. Discover the basics of JSON syntax, its applications, and why it has be...