Javascript | Link/Bookmarklet to remove variables in url

117 Views Asked by At

I found this and was able to do what I initially wanted. Javascript | Link/Bookmarklet to replace current window location

javascript:(function(){var loc=location.href;loc=loc.replace('gp/product','dp'); location.replace(loc)})()

Which was to change an amazon url from the product link to the dude perfect link.

It turns this url: https://www.amazon.com/gp/product/B01NBKTPTS/

into this url: https://www.amazon.com/dp/B01NBKTPTS/

I would like to take this a step further. Is there a way to do the above switch and then also remove the string of variables after the ? essentially cleaning up

https://www.amazon.com/gp/product/B01NBKTPTS/?pf_rd_r=DQV2YXJP8FFKM1Q50KS9&pf_rd_p=eb347dce-a775-4231-8920-ae66bdd987f4&pf_rd_m=ATVPDKIKX0DER&pf_rd_t=Landing&pf_rd_i=16310101&pf_rd_s=merchandised-search-2&linkCode=ilv&tag=onamzbybcreat-20&ascsubtag=At_Home_Cooking_210426210002&pd_rd_i=B01NBKTPTS

to

https://www.amazon.com/dp/B01NBKTPTS/

Thanks!

1

There are 1 best solutions below

0
On

You've almost done it yourself!

To do the second part you can use split on your /? string (i.e. URL).

In our case that will give you an array with two elements: the first element stores everything BEFORE the /? (reference [0], that's what we can use), and the other stores everything AFTER (reference [1], not needed for us)

FYI: if there were more /?, then split would produce an array with several elements. Additional information.

In addition, you shouldn't forget to escape the special character / this way: \/.

So here is the final working bookmarklet code to get the first URL part before /? letters, with gd/product replaced by dp:

javascript:(function(){
    var loc=location.href;
    loc=loc
            .split('\/?')[0]
            .replace('gp/product','dp')
            +'/';
    location.replace(loc);
 })();