Search code examples
url-rewritinggreasemonkey

greasemonkey script to replace a a letter in the url


I tried to modify some scripts I found - but they're not working.

When there is a link on a loaded page that points to: https://website.new/ia-o/number1/number2/number3/number4.jpeg.html

I want it to actually point to: https://website.new/ib-o/number1/number2/number3/number4.jpeg.html

So basically just replace one letter in the link (from */ia-o/* to */ib-o/*)

This is the script that I have tried:

// ==UserScript==
// @name        website.new
// @namespace   lii
// @description redirect to anothersite
// @include     https://website.new/*
// @version     1
// @grant       none
// ==/UserScript==

var links,thisLink;
links = document.evaluate("//a[@href]",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);

for (var i=0;i<links.snapshotLength;i++) {
    var thisLink = links.snapshotItem(i);

    thisLink.href = thisLink.href.replace('https://website.new/ia-o/',
                                          'https://website.new/ib-o/');

}

But it doesn't do anything.

If anyone can help - I'd greatly appreciate it!

Part2: Even better solution would be if I could remake the whole link like this.

Old link on a web page : https://website.new/ia-o/number1/number2/number3/number4.jpeg.html

New link on a page: https://website.new/o/number1/number2/number3/number4.jpeg

(so remove the ia- and also .html from the link)

But either solution would work!

Thank you!


Solution

  • replace href attribute in all links found in current page

    // ==UserScript==
    // @name        website.new
    // @namespace   lii
    // @description redirect to anothersite
    // @include     https://website.new/*
    // @version     1
    // @grant       none
    // ==/UserScript==
    
    (function() {
    
        for (var i=0,link; (link=document.links[i]); i++) {
            link.href = link.href.replace('oldvalue', 'newvalue');
        }
    
    })();
    

    you can replace single letters

    link.href.replace('a', 'o');
    

    or whole words

    link.href.replace('grease', 'tamper');
    

    in your specific case, just remove the strings you don't want by replacing them with an empty string

    link.href = link.href.replace(/ia-|\.html/g, '');