Search code examples
regexgreasemonkey

Replace parts of a URL in Greasemonkey


I'm trying to replace a part of url using a Greasemonkey script, but having hard time to achieve what I'm trying to do.

Original Urls are like:

http://x1.example.to/images/thumb/50/157/1571552600.jpg
http://x2.example.to/images/thumb/50/120/1201859695.jpg
http://x3.example.to/images/thumb/50/210/2109983330.jpg

What I want to achieve is this:

http://example.to/images/full/50/157/1571552600.jpg
http://example.to/images/full/50/120/1201859695.jpg
http://example.to/images/full/50/210/2109983330.jpg

I just want to replace thumb with full and cut out the x1.example.to, x2.example.to, x3.example.to, x4.example.to etc.. part completely from the original URL so new urls will be starting like example.to/images/full/

How do I achieve this?

I have found a Greasemonkey script from this answer and did try to work out but failed.

Here's what i did so far.

// ==UserScript==
// @name           Example Images Fixer
// @namespace      Example
// @description    Fixes image galleries
// @include        http://*.example.to/*
// ==/UserScript==

var links = document.getElementsByTagName("a"); //array
var regex = /^(http:\/\/)([^\.]+)(\.example\.to\/images\/thumb/\)(.+)$/i;
for (var i=0,imax=links.length; i<imax; i++) {
   links[i].href = links[i].href.replace(regex,"$4full/$5");
}

Any help on that?


Solution

  • You're forgetting to put the http:// part in your replacement URL:

    /^(https?:\/\/)[^.]+\.(example\.to\/images\/)thumb\/(.+)$/i
    

    and then:

    .replace(regex, "$1$2full/$3");
    

    You can see the results here.