JavaScript encodeURI() and decodeURI() Example


1. Overview of encodeURI() function

  • The encodeURI() function is used to encode a URI.
  • This function encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).
  • Note : Use the decodeURI() function to decode an encoded URI.

2. Overview of decodeURI() function

  • The decodeURI() function is used to decode a URI.
  • Note: Use the encodeURI() function to encode a URI.

3. encodeURI() and decodeURI() function example

Let's first encode using encodeURI() method and then decode it using decodeURI() function.
var uri = 'https://javaguides.net/?x=шеллы';
console.log("before encode :: " + uri);
var encoded = encodeURI(uri);
console.log("after encode :: " + encoded);
try {
    var decoded = decodeURI(encoded);
    console.log();
    console.log("after decode :: " + decoded);
} catch(e) { // catches a malformed URI
    console.error(e);
}
Output:
before encode :: https://javaguides.net/?x=шеллы
after encode :: https://javaguides.net/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B
after decode :: https://javaguides.net/?x=шеллы
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.

The following image shows testing encode and decode code examples from the browser's console tab:

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments