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 = 'шеллы';
console.log("before encode :: " + uri);
var encoded = encodeURI(uri);
console.log("after encode :: " + encoded);
try {
    var decoded = decodeURI(encoded);
    console.log("after decode :: " + decoded);
} catch(e) { // catches a malformed URI
before encode ::шеллы
after encode ::
after decode ::шеллы
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: