Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

JavaScript URL encode, decode and escape

0.00/5 (No votes)
4 Aug 2015 1  
A simple utility that provides JavaScript URL encode, decode and escape functionality

This article may contain live JavaScript that has been reviewed and tested for security. If you wish to submit articles containing JavaScript please email your submissions to submit@codeproject.com.

Introduction

I was sick of having to look up the difference between urlencode, encodeURIComponent and escape, so here's a quick online tool for those who need it.

 

The Code

<script type="text/javascript">
    function Process() {

        var source = document.getElementById('text');
        var text   = "" + source.value;
        var target = document.getElementById("result");
        var result = "";

        if (document.getElementById('encode').checked === true) {
            result += "<h4>urlEncode</h4><p>" + urlencode(text) + "</p>";
            result += "<h4>encodeURI</h4><p>" + encodeURI(text) + "</p>";
            result += "<h4>encodeURIComponent</h4><p>" + encodeURIComponent(text) + "</p>";
            result += "<h4>escape</h4><p>" + escape(text) + "</p>";
        }
        else {
            result += "<h4>urldecode</h4><p>" + urldecode(text) + "</p>";
            result += "<h4>decodeURI</h4><p>" + decodeURI(text) + "</p>";
            result += "<h4>decodeURIComponent</h4><p>" + decodeURIComponent(text) + "</p>";
            result += "<h4>unescape</h4><p>" + unescape(text) + "</p>";
        }

        target.innerHTML = result;
    }

    function urlencode(text) {
        return encodeURIComponent(text).replace(/!/g,  '%21')
                                       .replace(/'/g,  '%27')
                                       .replace(/\(/g, '%28')
                                       .replace(/\)/g, '%29')
                                       .replace(/\*/g, '%2A')
                                       .replace(/%20/g, '+');
    }
    function urldecode(text) {
        return decodeURIComponent((text + '').replace(/\+/g, '%20'));
    }
</script>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here