Search code examples
javascriptjqueryuserscripts

&-sign is ruining my link-rewriter


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

Solution

  • 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);