The beginner's guide to Greasemonkey scripting

How to make the web work exactly as you want it to

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 juliet/
// @description Replace "incentivize" on corporate homepage
// @include
// ==/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); =, 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