JavaScript encodeURIComponent() and decodeURIComponent() Example

1. Overview of encodeURIComponent() function

To encode full URI then check out JavaScript encodeURI() and decodeURI() Example article.
  • The encodeURIComponent() function encodes a URI component.
  • This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #
  • Note: Use the decodeURIComponent() function to decode an encoded URI component.

2. Overview of decodeURIComponent() function

  • The decodeURIComponent() function decodes a URI component.
  • Note: Use the encodeURIComponent() function to encode a URI component.

3. encodeURIComponent() and  decodeURIComponent() function example

Let's first encode URL using encodeURIComponent() method and then decode it using decodeURIComponent() function:
var uri = "https://javaguides.net/my test.html?name=ram&age29";
console.log("before encode :: " + uri);
var encode = encodeURIComponent(uri); 
console.log("after encode :: " + encode);

var decode = decodeURIComponent(encode);
console.log("after decode :: " + decode);
Output:
before encode :: https://javaguides.net/my test.html?name=ram&age29
after encode :: https%3A%2F%2Fjavaguides.net%2Fmy%20test.html%3Fname%3Dram%26age29
after decode :: https://javaguides.net/my test.html?name=ram&age29
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 URI component and decode URI component code examples from the browser's console tab:

Next post, check out JavaScript encodeURI() and decodeURI() Example

Comments