ixchi
ixchi

Reputation: 2389

decodeURI not fully working

I'm trying to remove the URI encoding from a link, but decodeURI doesn't seem to be fully working.

My example link is this: /linkout?remoteUrl=http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-heroic-armies-marching

After running the JavaScript script, it looks like this:

http%3a%2f%2fsandbox.yoyogames.com%2fgames%2f171985-h-a-m-heroic-armies-marching

How can I get rid of the remaining not correct codes in the URI?

My decoding code:

var href = $(this).attr('href');            // get the href
var href = decodeURI(href.substring(19));   // remove the outgoing part and remove the escaping
$(this).attr('href', 'http://'+href)        // change link on page

Upvotes: 30

Views: 39388

Answers (3)

anlijudavid
anlijudavid

Reputation: 539

My implementation is a recursive function:

export function tryDecodeURLComponent(str: string, maxInterations = 30, iterations = 0): string {
    if (iterations >= maxInterations) {
        return str;
    } else if (typeof str === 'string' && (str.indexOf('%3D') !== -1 || str.indexOf('%25') !== -1)) {
        return tryDecodeURLComponent(decodeURIComponent(str), maxInterations, iterations + 1)
    }

    return decodeURIComponent(str);
}
  • str: encoded string.
  • maxInterations: Maximum recursive iterations to try decoding str (default: 30).
  • iterations: Flag counter iteration.

Upvotes: 2

Michael Blake
Michael Blake

Reputation: 41

I just encountered this situation in an ASHX handler for the PUT verb. ASP.NET is apparently encoding my XML for me, so my server-side call to HttpUtility.UrlEncode was not needed. Fixing it by calling client-side Javascript decodeURI twice -- is closing the barn door after the cows have already left and the HTTP I was sending was a protocol violation.

I would have commented and plus-one'd Tobias Krogh's answer, but I don't have the points to do so…

However, I still think that it is important to note that the failure being discussed here is not a Javascript decodeURI or anything else -- it is a data validation error.

Upvotes: 1

Tobias Krogh
Tobias Krogh

Reputation: 3932

the url looks as it was encoded twice, I also suggest to use decodeURIComponent

decodeURIComponent(decodeURIComponent("http%253a%252f%252fsandbox.yoyogames.com%252fgames%252f171985-h-a-m-heroic-armies-marching"))

results in: "http://sandbox.yoyogames.com/games/171985-h-a-m-heroic-armies-marching"

but you should check why you have the url encoded twice in advance

Upvotes: 73

Related Questions