The Correct Way to Use URL Decoding: Differences Between decodeURI and decodeURIComponent

目次

Overview

To use data received via URL parameters—such as Japanese search keywords—in a web application, it is essential to perform “decoding.” This process converts the encoded string back to its original format. This article explains the decisive differences between the two JavaScript decoding functions, decodeURI and decodeURIComponent, and how to use them correctly in actual development.

Specifications (Input/Output)

Method Comparison

Both methods convert percent-encoded strings (%xx) back to their original characters, but they target different ranges of characters.

MethodPurposeKey Behavior
decodeURI(str)Decodes an entire URLDoes not decode reserved characters with special meanings in a URL (e.g., ; / ? : @ & = + $ , #).
decodeURIComponent(str)Decodes a URL componentDecodes all encoded values back into characters. This is the correct choice for reading parameter values.
  • Input: An encoded string.
  • Output: A decoded string.
  • Exception: If the encoding format is invalid (e.g., a % followed by inappropriate characters), a URIError will be thrown.

Basic Usage

1. Restoring an Entire URL (decodeURI)

Use this when you want to restore a full URL that was encoded with encodeURI. It is suitable when you need to maintain the URL structure, such as slashes and question marks.

// The structure of the URL is preserved
const url = 'https://example.com/%E6%A4%9C%E7%B4%A2';
console.log(decodeURI(url)); 
// Output: "https://example.com/search"

2. Reading Parameter Values (decodeURIComponent)

Use this when you want to restore the complete original text data, such as a query parameter value.

// All characters, including slashes (%2F), are restored
const param = '%E6%9D%B1%E4%BA%AC%2F%E6%B8%8B%E8%B0%B7';
console.log(decodeURIComponent(param)); 
// Output: "Tokyo/Shibuya"

Full Code

This is a simulation that retrieves a search keyword from a URL query parameter (?q=...) and displays it on the screen. Since parameter values may contain symbols easily mistaken for URL delimiters, we use the powerful decodeURIComponent.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Decoding Demo</title>
    <style>
        .result-panel {
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 8px;
            font-family: sans-serif;
            max-width: 400px;
            background-color: #f9f9f9;
        }
        .keyword {
            color: #d32f2f;
            font-weight: bold;
            font-size: 1.2em;
        }
        .label {
            font-size: 0.9em;
            color: #666;
        }
    </style>
</head>
<body>

<div class="result-panel">
    <p class="label">Current Search Keyword:</p>
    <p>"<span id="output-keyword" class="keyword"></span>"</p>
</div>

<script src="decoder.js"></script>
</body>
</html>

JavaScript

/**
 * Function to retrieve and decode a value from a query string
 * @param {string} queryString - The query string to analyze (e.g., "?q=%E3%83...")
 * @param {string} key - The parameter name to retrieve
 * @returns {string|null} The decoded value or null
 */
const getDecodedParam = (queryString, key) => {
    // Remove the leading '?' and split the string
    const params = queryString.substring(1).split('&');
    
    for (const param of params) {
        const [currentKey, currentValue] = param.split('=');
        
        if (currentKey === key && currentValue) {
            try {
                // Execute decoding safely
                return decodeURIComponent(currentValue);
            } catch (e) {
                console.error('URI decoding failed:', e);
                return currentValue; // Fallback to raw value on failure
            }
        }
    }
    return null;
};

// Main execution
const init = () => {
    const outputElement = document.getElementById('output-keyword');
    
    // Mock URL parameters (In production, use window.location.search)
    // q = "JavaScript & HTML" (%26 is an ampersand)
    const mockQueryString = '?category=tech&q=JavaScript%20%26%20HTML';

    const keyword = getDecodedParam(mockQueryString, 'q');

    if (keyword) {
        outputElement.textContent = keyword;
    } else {
        outputElement.textContent = 'None';
    }
};

// Execute after DOM is fully loaded
document.addEventListener('DOMContentLoaded', init);

Customization Points

To use this in a production environment, replace the mockQueryString variable with window.location.search. Additionally, some older systems encode spaces as + instead of %20. You can increase compatibility by adding a .replace(/\+/g, ' ') process before running decodeURIComponent.

Important Notes

When decoding data from external sources, always wrap the process in a try...catch block, as an invalid percent-encoding sequence will cause the script to stop with a URIError. From a security standpoint, never display decoded strings using innerHTML, as they may contain malicious scripts. Use textContent instead to ensure the data is treated strictly as text. Furthermore, remember that decodeURI does not decode symbols like / (%2F) or ? (%3F), which can lead to unexpected results if your parameter data contains these characters.

Advanced Usage

In modern browsers, you can use the URLSearchParams API, which is specifically designed for parsing parameters. This API automatically handles decoding internally, making your code even simpler.

const queryString = '?q=JavaScript%20%26%20HTML';
const params = new URLSearchParams(queryString);

// The get method automatically decodes the value
const keyword = params.get('q'); 

console.log(keyword); // Output: "JavaScript & HTML"

Summary

The basic strategy for URL decoding is to use decodeURIComponent for retrieving specific parameter values, as it has the most comprehensive conversion capabilities. Only use decodeURI if you specifically need to keep the URL structure intact while improving readability. Because decoding processes are prone to errors and security risks, always include proper exception handling and protections against cross-site scripting.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次