Part 4 - Replace text

Next up, let's take a look at replacing text that occurs anywhere in a webpage. Perhaps you are particularly fed up with the word "incentivize" occurring repeatedly in your corporate homepage, which, distressingly, you are required to look at on a regular basis. Let's replace it with "pling" instead (or any other word you find mildly amusing, rather than eyeball-spork-inducing).

// ==UserScript==
// @name Deincentivize
// @namespace http://www.example.com/ juliet/
// @description Replace "incentivize" on corporate homepage
// @include http://www.example.net/corporatehome
// ==/UserScript==
textNodes = document.evaluate(
"//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var searchRE = new RegExp('incentivize','gi');
var replace = 'pling';
for (var i=0;i<textNodes.snapshotLength;i++) {
var node = textNodes.snapshotItem(i);
node.data = node.data.replace(searchRE, replace);

The first section of code should be familiar from our earlier script. It looks for any text nodes in the document. Next we set up the regular expression.

The constructor new RegExp() takes two arguments. The first is the string that you're looking for. The second is the modifier. g means global match – replace every occurrence of the string, not just the first one. (Most of the time, you'll want to use this.) i makes the match case-insensitive.

There's also m for multi-line mode, which makes the start-of-line and end-of-line anchors (^ and $) match before and after newlines rather than matching the ends of the text in the node.

Finally, there's another for loop to do the real work of going through the XPath query output, looking for our search string, and replace it with our replace string. Easy!

There's a vast amount more you can do with Greasemonkey – the key is to start experimenting and see what changes you can make. Have fun remoulding the web to your own preferences!

-------------------------------------------------------------------------------------------------------

First published in Linux Format Issue 118

Like this article? Then check out 8 hacks to make Firefox ridiculously fast

Sign up for the free weekly TechRadar newsletter
Get tech news delivered straight to your inbox. Register for the free TechRadar newsletter and stay on top of the week's biggest stories and product releases. Sign up at http://www.techradar.com/register

Follow TechRadar on Twitter