It turns out the piece of the puzzle I needed to find was something called back references. What it basically means is that if you put brackets around a part of the expression that’s being matched, anything matched by the part of the expression in brackets is put in a variable that you can access in your replace string.
This makes regular expressions really, really powerful because you can easily manipulate text in ways that previously would have involved using substring and indexof and length functions (which always make me groan quietly to myself as I hack at the code until the thing gets me the right part of the string).
The example today was I wanted to find certain parts of text in an element of my webpage and highlight them with a bold tag. My new found knowledge of back references made this simple:
var newstring = oldstring.replace(new RegExp("(" + keyword + ")"), "<strong>$1</strong>");