Search code examples
javascriptregexgreasemonkey

Change the URL using GreaseMonkey


I want to change the current URL of the page with a Greasemonkey script.

I mean, I'm at the location : "http://www.mywebsite.com/video/old/*.mkv" and I want to move to "http://www.mywebsite.com/video/new/*.mkv". So basically, I just want to change the "old" in "new" in the URL.

I have found this code :

var oldUrlPath  = window.location.pathname;

/*--- Test that ".compact" is at end of URL, excepting any "hashes"
or searches.
*/
    var newURL  = window.location.protocol + "//"
            + window.location.host 
            + oldURLPath
            + window.location.search
            + window.location.hash
            ;
     /*-- replace() puts the good page in the history instead of the
    bad page.
    */
    window.location.replace (newURL);

But I don know how to replace the oldURLPath by the newURLPath I want. I think I must use replace() But I'm not sure (And all the code I try don't work, I must don't use it correctly cause I'm not familiar with ReGex).

Thanks for your answer


Solution

  • I don't see any need in regex. Looks like you could just replace() old with new.

    var oldURL = "http://www.mywebsite.com/video/old/*.mkv";
    location.href = oldURL.replace('old','new');