0
0
JavascriptHow-ToBeginner · 3 min read

How to Decode URL in JavaScript: Simple Guide

To decode a URL in JavaScript, use the decodeURIComponent() function to decode encoded parts of a URL, or decodeURI() to decode a full URL without affecting reserved characters. These functions convert percent-encoded characters back to normal characters.
📐

Syntax

The two main functions to decode URLs in JavaScript are:

  • decodeURIComponent(encodedURIComponent): Decodes a URL component by converting percent-encoded characters to normal characters.
  • decodeURI(encodedURI): Decodes a full URL but leaves reserved characters like ?, #, and & intact.
javascript
decodeURIComponent(encodedURIComponent)
decodeURI(encodedURI)
💻

Example

This example shows how to decode a URL component and a full URL using decodeURIComponent() and decodeURI() respectively.

javascript
const encodedComponent = 'Hello%20World%21';
const decodedComponent = decodeURIComponent(encodedComponent);

const encodedURL = 'https%3A%2F%2Fexample.com%2Fsearch%3Fq%3DJavaScript%2520decode';
const decodedURL = decodeURIComponent(encodedURL);

console.log('Decoded Component:', decodedComponent);
console.log('Decoded URL:', decodedURL);
Output
Decoded Component: Hello World! Decoded URL: https://example.com/search?q=JavaScript%20decode
⚠️

Common Pitfalls

A common mistake is using decodeURI() on URL components, which can cause errors if the component contains characters that should be decoded. Also, decoding an already decoded string can cause errors or unexpected results.

Always use decodeURIComponent() for parts of URLs like query parameters, and decodeURI() for full URLs.

javascript
try {
  // Wrong: decoding a component with decodeURI
  const wrong = decodeURI('Hello%20World%21');
  console.log('Wrong decoding:', wrong);
} catch (e) {
  console.log('Error:', e.message);
}

// Correct way
const right = decodeURIComponent('Hello%20World%21');
console.log('Correct decoding:', right);
Output
Wrong decoding: Hello World! Correct decoding: Hello World!
📊

Quick Reference

Use this quick guide to choose the right decoding function:

FunctionUse CaseEffect on Reserved Characters
decodeURIComponent()Decode URL parts like query parametersDecodes all percent-encoded characters
decodeURI()Decode full URLsLeaves reserved characters (%3F, %23, etc.) intact

Key Takeaways

Use decodeURIComponent() to decode individual URL parts like query parameters.
Use decodeURI() to decode a full URL without changing reserved characters.
Avoid decoding an already decoded string to prevent errors.
decodeURIComponent() decodes all percent-encoded characters, decodeURI() preserves reserved characters.
Test your decoded output to ensure it matches the expected readable URL.