0

I'm currently writing a userscript that runs on another site. One function is to rewrite the links so you skip one landing page. However, if the &-sign exists in the link, my function will output it as & instead of &.

        $('a').each(function(index) {
        var aLink = $(this).attr('href');
        if(aLink) {
            if(aLink.indexOf("leave.php?u=") > 0) {
                aLink = aLink.substring(38);
                $(this).attr('href', decodeURIComponent(aLink));
            }

        }
    });

This is one example of a link that gets ruined:

 https://www.site.com/exit.php?u=http%3A%2F%2Fsverigesradio.se%2Fsida%2Fartikel.aspx%3Fprogramid%3D104%26amp%3Bartikel%3D3406950

Is a link to:

 http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950

But becomes this instead:

 http://sverigesradio.se/sida/artikel.aspx?programid=104&artikel=3406950
4
  • 1
    It is double encoded, so you should also double decode it.
    – Rene Pot
    Jan 30, 2012 at 13:14
  • @Topener, you mean like just apply decodeURIComponent twice? Jan 30, 2012 at 13:34
  • @mgraph, tried that and got a relative link, not absolute. Jan 30, 2012 at 13:34
  • @Topener, it doesn't solve it. Jan 30, 2012 at 15:08

1 Answer 1

1

The & entity is built right into that URL, so there's nothing for it except to just replace it.

Use:

aLink = aLink.substring (38);
aLink = decodeURIComponent (aLink);
aLink = aLink.replace (/&/gi, "&");
$(this).attr ('href', aLink);
2
  • This doesn't seem like a adaptable solution if the same occurs with any other sign... Jan 30, 2012 at 15:10
  • It doesn't occur with any other character, and & is not a "sign" it is an entity -- which is a very specific thing in HTML. You only need be concerned where entities (that are actually used) overlap deliminator characters for URL's. That's just & and no others. Jan 30, 2012 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.