Help with replace url Greasemonkey Script

I am trying to learn some javascript at the moment and thought a simple greasemonkey script might be a good way to start.

What I want the script to do is to replace an existing url on a website with a different url from another location within the website.

E.G. replace “/mailbox.php?inbox” with “/account.php?action=mybookmarks”

There are a lot of examples of replacing existing urls with different ones on the web but they all use id’s to locate and replace urls.

This script is for a site I visit often and since I dont own it I dont have the ability to add id tags to the appropriate a tags, this makes writing this script a lot more difficult.

This is the code I have so far;

// ==UserScript==
// @name         NZBmatrix mailbox url replace
// @include      http://nzbmatrix.com/
// @description  replace "/mailbox.php?inbox" with "/account.php?action=mybookmarks"
// ==/UserScript==

    function urlreplace()
{
    var allLinks = document.links;

    if (allLinks != null)
	{
		for (i = 0; i <allLinks.length; ++i)
			{
				if (allLinks [i].href.indexOf ("/mailbox.php?inbox") > 0)
				{
				allLinks [i].href = allLinks [i].href.replace ("/account.php?action=mybookmarks");
				}
			}
	}
};

any help or tips would be much appreciated

I’d agree that GM is a good way to learn JS, especially DOM manipulation.

The document.links collection is not something you should be using really. Instead, document.getElementsByTagName(‘a’) is a better way.

allLinks is never going to be null. It will just be an empty HTML collection object if there are no links. Better is to check the length of it.

Your replace() won’t work because you are missing a parameter: what to search for. Have a look at the documentation. Also, the replace will only work if the search parameter is present, so checking if it’s present (indexOf) is redundant.

The code I posted is not my own, it is another script I found which I thought I could modify to suit my needs. It seems I was on the wrong track using this script as a starting point.

So I guess I should start from scratch again by writing some psuedocode and then writing the javascript from that?

Yes, or just write some JavaScript straight away. You can use the code you posted as pseudo-code. It just needs some very simple modifications (see my other post).