Search code examples
javascriptstringurlgreasemonkey

Greasemonkey remove string from url without regex


If I have a webpage with referral strings on every URL which I want to remove with greasemonkey, How can I do that?

For example:

<a href="https://website.refer?url=www.google.com"> The link </a>

The link

Changed to:

<a href="www.google.com"> The link </a>

The link

How can I remove the "/website.refer?url=" part of the URL?

I've tried things such as:

document.getElementsByTagName("a").replace('/website.refer?url=','');

Yet nothing I try seems to work See fiddle: Here

Please no regex. Thanks


Solution

  • Iterate over every <a>, get the url parameter via URLSearchParameters, and assign it to the href of the <a>:

    document.querySelectorAll('a').forEach((a) => {
      const params = new URLSearchParams(a.href.split('?')[1]);
      a.href = '//' + params.get('url');
    });
    <a href="https://website.refer.com?url=www.google.com"> The link </a>