0

I have an Image URL for which decodeURIComponent is faling. I tried it with unescape as well, still no luck. I can not use JQuery here. I need a solution which uses plain JS to resolve this issue.

I have not given actual code, but here is a code snippet with URL to be encoded and decoded.

Encode URL function works fine but the Decode function fails.

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to encode and decode a URI.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var uri = "http://lp.imageg.net/prod?set=key[initials],value[ABC]&set=key[color],value[blind stamp]&set=key[displaysize],value[64%]&load=url[http://chains.imageg.net/graphics/dynamic/chains/TUMI_TAG1.chain]";
var uri_enc = "Encoded URI: " + encodeURIComponent(uri);
alert(uri_enc);
var uri_dec = "Decoded URI: " + decodeURIComponent(unescape(uri));
var uri_dec = "Decoded URI: " + decodeURIComponent(uri);
alert(uri_dec);
var res = uri_enc + "<br>" + uri_dec;
document.getElementById("demo").innerHTML=res;

}
</script>

</body>
</html> 
Learn More
  • 1,535
  • 4
  • 29
  • 51

1 Answers1

1

You were doing it incorrectly...here's updated code...

Demo Fiddle

    <!DOCTYPE html>
    <html>
    <body>
    <p id="demo">Click the button to encode and decode a URI.</p>
    <button onclick="myFunction()">Try it</button>
    <script>
        function myFunction() {
            var uri = "http://lp.imageg.net/prod?set=key[initials],value[ABC]&set=key[color],value[blind stamp]&set=key[displaysize],value[64%]&load=url[http://chains.imageg.net/graphics/dynamic/chains/TUMI_TAG1.chain]";
            var uri_enc = "Encoded URI: " + encodeURIComponent(uri).replace(/'/g, "%27").replace(/"/g, "%22");
            alert(uri_enc);
            var uri_dec = "Decoded URI: " + decodeURIComponent(uri_enc.replace(/\+/g, " "));
            alert(uri_dec);
            var res = uri_enc + "<br>" + uri_dec;
            document.getElementById("demo").innerHTML = res;

        }
    </script>
</body>
    </html> 
Nikhil N
  • 4,507
  • 1
  • 35
  • 53