Back referencing in javascript regular expressions

I’ve used regular expressions to do find and replace Javascript before, but I’ve never managed to do the thing where you can take part of the string that has been matched and use it in the replace string.

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:

  1. var newstring = oldstring.replace(new RegExp("(" + keyword + ")"), "<strong>$1</strong>");

While I was doing this, I also found a really useful Introduction to regexp in javascript tutorial that includes some great tables of the different flags and modifiers.

Posted on 21 Jul 05 by Helen Emerson (last updated on 21 Jul 05).
Filed under Javascript