Differences between decodeURI and decodeURIComponent

The main differences are:

  • encodeURI is intended to be used on the full URI.
  • encodeURIComponent is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

    So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

    Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

    so in your case decodeURIComponent does the job

  • Answer from vireshas on Stack Overflow
    🌐
    MDN Web Docs
    developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › decodeURI
    decodeURI() - JavaScript - MDN Web Docs
    const uri = "https://mozilla.org/?x=шеллы"; const encoded = encodeURI(uri); console.log(encoded); // Expected output: "https://mozilla.org/?x=шеллы" try { console.log(decodeURI(encoded)); // Expected output: "https://mozilla.org/?x=шеллы" } catch (e) { // Catches a malformed URI console.error(e); } ... A complete, encoded Uniform Resource Identifier. A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI).
    Discussions

    javascript - Decode a run-length encoded string - Stack Overflow
    I'm trying to implement the Decode String algorithm in javascript. The LeetCode Problem 394. Decode String is: Given an encoded string, return its decoded string. The encoding rule is: k[encoded_s... More on stackoverflow.com
    🌐 stackoverflow.com
    Blueprint String decoder in Javascript?
    I am working on a blueprint sharing site along the lines of Factorioprints, so that required me to figure this out. Here is the file that I made. It's pretty simple. If you're on the front-end, the only NPM package you need to install is Pako. If you're on a Node server, you need to install atob and btoa as well. More on reddit.com
    🌐 r/factorio
    9
    6
    August 4, 2020
    Replace Unicode in a string with its symbol...
    If the characters are encoded as HTML entities, which it sounds like they are, you can decode them using the built in String.fromCharCode() method: str.replace(/&#(\d+);/g, (m, d) => String.fromCharCode(d)); Here's a quick fiddle More on reddit.com
    🌐 r/learnjavascript
    8
    4
    September 8, 2018
    GDPR Cookie decoding
    Generally with much wailing and gnashing of teeth, as far as I can tell. The encoding heavily favours compactness over ease of use. Quantcast has a tool for building cookies here , but it won't decode a cookie value. If no one else has done it by the weekend, I'll probably knock up a quick web page to do it. More on reddit.com
    🌐 r/adops
    6
    2
    May 22, 2018
    🌐
    MDN Web Docs
    developer.mozilla.org › en-US › docs › Web › API › TextDecoder › decode
    TextDecoder: decode() method - Web APIs - MDN Web Docs
    June 23, 2025 - The TextDecoder.decode() method returns a string containing text decoded from the buffer passed as a parameter.
    🌐
    Telerik
    telerik.com › blogs › encode-and-decode-strings-using-javascript
    Encode and Decode strings using JavaScript
    May 27, 2021 - In order for a string to be read from all computers sometimes it is useful to encode and decode it. This can be easily achieved using the JavaScript built-in escape() and unescape() methods.
    🌐
    Coderstoolbox
    coderstoolbox.net › string
    Online JavaScript string decoder
    Encode and decode strings: Base64, URL, XML, JavaScript
    🌐
    DigitalOcean
    digitalocean.com › community › tutorials › how-to-encode-and-decode-strings-with-base64-in-javascript
    How To Encode and Decode Strings with Base64 in JavaScript | DigitalOcean
    Learn how to encode and decode strings with Base64 in JavaScript. This guide covers btoa(), atob(), Buffer, modern APIs, and practical examples.
    🌐
    GeeksforGeeks
    geeksforgeeks.org › javascript › javascript-encode-decode-a-string-to-base64
    JavaScript | Encode/Decode a string to Base64 - GeeksforGeeks
    May 28, 2024 - Parameter (String): This parameter is required. It specifies the string to be encoded. This method decodes a base-64 encoded string, which has been encoded by the btoa() method.
    Find elsewhere
    🌐
    W3Schools
    w3schools.com › jsref › jsref_decodeuri.asp
    JavaScript decodeURI() Method
    The decodeURI() method decodes a URI. ... Coding fundamentals as bite-sized lessons and challenges. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
    🌐
    Techfunda
    techfunda.com › howto › 908 › decode-a-string
    Decode a string in JavaScript - Tech Funda
    To decode a string we need the encoded string, for that first we are usnig escape() function to encode the string in varaible e, and then unescape() function to decode the encoded string.
    🌐
    TutorialsPoint
    tutorialspoint.com › article › how-to-decode-an-encoded-string-in-javascript
    How to decode an encoded string in JavaScript?
    March 15, 2026 - While unescape() can decode escaped strings, use decodeURIComponent() or decodeURI() for modern JavaScript applications as they provide better UTF-8 support and follow current standards.
    🌐
    Node.js
    nodejs.org › api › string_decoder.html
    String decoder | Node.js v26.7.0 Documentation
    The node:string_decoder module provides an API for decoding Buffer objects into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 characters.
    🌐
    DEV Community
    dev.to › catur › simple-encode-and-decode-with-javascript-od6
    Simple Encode And Decode With Javascript - DEV Community
    February 14, 2023 - Javascript has several methods for doing this, but in this short article, we'll try to do it easily and practically. One method that is quite popular for encoding and decoding a string is base64. For those who are familiar with the PHP language, this method seems familiar.
    🌐
    TutorialsPoint
    tutorialspoint.com › function-to-decode-a-string-in-javascript
    decodeURIComponent() function in JavaScript
    August 23, 2023 - The decodeURIComponent() function accepts a string value representing an encoded URI (Uniform Resource Identifier), decodes it, and returns the result.
    🌐
    GeeksforGeeks
    geeksforgeeks.org › how-to-encode-and-decode-a-url-in-javascript
    How to Encode and Decode a URL in JavaScript? | GeeksforGeeks
    September 2, 2024 - The hexadecimal sequence in the string is replaced by the characters they represent when decoded via unescape() function.
    🌐
    Intervue
    intervue.io › top-coding-questions › javascript › encode-and-decode-strings
    Encode & Decode Strings problem in JavaScript – Optimize Code
    function encode(strs) { return strs.join('\n'); } function decode(str) { return str.split('\n'); } How would you handle the case where the input strings contain the delimiter?
    🌐
    GeeksforGeeks
    geeksforgeeks.org › javascript-unescape
    JavaScript unescape() Function - GeeksforGeeks
    May 23, 2023 - The Javascript unescape() function in JavaScript takes a string as a parameter and uses it to decode that string encoded by the escape() function.
    Top answer
    1 of 4
    5

    You could replace the string with a regular expression and get the wanted nested replacements until no more strings are available to replace.

    const decodeString = string => {
    let repeat
    do {
        repeat = false;
        string = string.replace(/(\d+)\[([^\[\]]+)\]/g, (_, c, v) => {
            repeat = true;
            return v.repeat(c);
        });
    } while (repeat);
    return string;
    }
    
    console.log(decodeString("3[a]2[bc]")); // "aaabcbc"
    console.log(decodeString("3[a2[c]]")); // "accaccacc"
    console.log(decodeString("2[abc]3[cd]ef")); // "abcabccdcdcdef"
    console.log(decodeString("abc3[cd]xyz")); // "abccdcdcdxyz"
    Run code snippetEdit code snippet Hide Results Copy to answer Expand


    If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.


    RegEx Circuit

    jex.im visualizes regular expressions:

    2 of 4
    3

    This answer is creative and good; we can also use stack for solving this problem.

    This'll get accepted:

    const decodeString = s => {
        const stack = [];
        for (const char of s) {
            if (char !== "]") {
                stack.push(char);
                continue;
            }
    
            let currChar = stack.pop();
            let decoded = '';
            while (currChar !== '[') {
                decoded = currChar.concat(decoded);
                currChar = stack.pop();
            }
    
            let num = '';
            currChar = stack.pop();
    
            while (!Number.isNaN(Number(currChar))) {
                num = currChar.concat(num);
                currChar = stack.pop();
            }
    
            stack.push(currChar);
            stack.push(decoded.repeat(Number(num)));
        }
    
        return stack.join('');
    };
    
    console.log(decodeString("3[a]2[bc]"))
    console.log(decodeString("3[a2[c]]"))
    console.log(decodeString("2[abc]3[cd]ef"))
    console.log(decodeString("abc3[cd]xyz"))
    Run code snippetEdit code snippet Hide Results Copy to answer Expand

    In Python, we would similarly use a list, which is very similar to JavaScript's array:

    class Solution:
        def decodeString(self, base_string):
            stack = []
            decoded = ''
            full_num = 0
    
            for char in base_string:
                if char == '[':
                    stack.append(decoded)
                    stack.append(full_num)
                    decoded, full_num = '', 0
                elif char == ']':
                    curr_digit, curr_char = stack.pop(), stack.pop()
                    decoded = curr_char + curr_digit * decoded
                elif char.isdigit():
                    full_num *= 10
                    full_num += int(char)
                else:
                    decoded += char
    
            return decoded
    

    In Java, we would have used two Stacks:

    class Solution {
        public String decodeString(String string) {
            String decoded = "";
            Stack<Integer> numberStack = new Stack<>();
            Stack<String> decodedStack = new Stack<>();
            int count = 0;
    
            while (count < string.length()) {
                if (Character.isDigit(string.charAt(count))) {
                    int fullNum = 0;
    
                    while (Character.isDigit(string.charAt(count))) {
                        fullNum = 10 * fullNum + (string.charAt(count) - '0');
                        count++;
                    }
    
                    numberStack.push(fullNum);
    
                } else if (string.charAt(count) == '[') {
                    decodedStack.push(decoded);
                    decoded = "";
                    count++;
    
                } else if (string.charAt(count) == ']') {
                    StringBuilder temp = new StringBuilder(decodedStack.pop());
                    int repeatTimes = numberStack.pop();
    
                    for (int iter = 0; iter < repeatTimes; iter++)
                        temp.append(decoded);
    
                    decoded = temp.toString();
                    count++;
    
                } else
                    decoded += string.charAt(count++);
            }
    
            return decoded;
        }
    }
    

    References

    • For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
    🌐
    freeCodeCamp
    freecodecamp.org › news › encode-decode-html-base64-using-javascript
    How to Encode and Decode HTML Base64 using JavaScript – JS Encoding Example
    November 7, 2024 - The resulting binary data is a reconstruction of the original binary data encoded to Base64. To encode and decode in JavaScript, you will use the btoa() and atob() JavaScript functions that are available and supported by modern web browsers.
    🌐
    URLDecoder
    urldecoder.io › javascript
    How to Decode URI components in Javascript | URLDecoder
    You can decode URI components in Javascript using the decodeURIComponent() function. It performs the inverse operation of encodeURIComponent(). It uses UTF-8 encoding scheme to decode URI components. The decodeURIComponent() function converts a URL encoded string back to its normal form.