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?

After running the JavaScript script, it looks like this:

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

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


results in:

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

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.

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…

Read More:   Disable web page navigation on swipe(back and forward)

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.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts