View Full Version : Regular Expression Help

10-13-2003, 07:17 PM
OK I am wanting a RegularExpression which will match a few different words (ie. a|b|c|d) and then replace the matched word with itself enclosed in <b></b> or some other such HTML tag.

Currently I am having to run a different RegExp for each word

var GT2 = GT.replace(/ O:/g, " <br><b>O:</b>");
var GT3 = GT2.replace(/ SO:/g," <br><b>SO:</b>");
var GT4 = GT3.replace(/ R:/g," <br><b>R:</b>");
var GT5 = GT4.replace(/ WL:/g," <br><b>WL</b>");

What I want is something like

var GT2 = GT.replace (/ O:| SO:| R:| WL:/g, "<br><b>word replaced here</b>")

Is there any way to do this?

Thanks for any help


10-13-2003, 07:55 PM
yup -- they're called backreferences, or, remembered matches.

GT = GT.replace(/(O:|SO:|R:|WL:)/g, " <br><b>$1</b>");

With some exceptions, any parenthical in a pattern creates a remembered match, which you reference by it's number, up to 9. As you can see, the syntax for placing a remembered match into the replacement is "dollar-sign reference number"

Check into a good tutorial on regular expressions, they will cover this topic better.

10-13-2003, 10:00 PM
Cool thanks beetle, I knew I had done this before in other languages but couldn't remember what it was called!


10-13-2003, 10:08 PM
You could have a look at the RegExp tutorials at Evolt and Website Abstraction:

1. <http://evolt.org/article/rating/20/22700/index.html>
2. <http://evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/index.html>
2. <http://wsabstract.com/javatutors/redev.shtml>
3. <http://wsabstract.com/javatutors/re.shtml>