What are the encodeURI() and decodeURI() in JavaScript ?


encodeURI() and decodeURI() are two built-in functions in JavaScript that are used to encode and decode a URI (Uniform Resource Identifier) respectively.

encodeURI() function is used to encode a complete URI by replacing certain characters with their corresponding UTF-8 escape sequences. This function encodes all characters except the following: A-Z, a-z, 0-9, -, _, ., !, ~, *, ', (, ).

For example:

const uri = "https://www.example.com/search?q=JavaScript&lang=en";
const encodedURI = encodeURI(uri);
console.log(encodedURI); // "https://www.example.com/search?q=JavaScript&lang=en"

decodeURI() function is used to decode a URI that has been encoded using encodeURI(). This function replaces all UTF-8 escape sequences with their corresponding characters.

For example:

const encodedURI = "https://www.example.com/search?q=JavaScript%26lang%3Den";
const decodedURI = decodeURI(encodedURI);
console.log(decodedURI); // "https://www.example.com/search?q=JavaScript&lang=en"

It is important to note that encodeURI() and decodeURI() do not encode or decode the entire URL. They only encode or decode the individual components of the URL, such as the query string or the path. If you need to encode or decode the entire URL, you can use encodeURIComponent() and decodeURIComponent() functions.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.