views:

35

answers:

1

If you use the regular expression /(this|a)/

Now if I have:

var text = "this is a sentence.";
text = text.replace(/(this|a)/gi, "_");
document.write(text);

I get the output: _ is _ sentence

I am working on a piece of Javascript that does selective styling so what I want to do is add '<span class="className">" + word_in_regex + "</span>" where word_in_regex is the word from the expression that has been matched. Is this possible or no?

+3  A: 

You can use $1 in the replacement string to reference the match of the first group:

"this is a sentence".replace(/(this|a)/g, "_$1_")  // returns "_this_ is _a_ sentence"

Note the g flag to replace globally; otherwise only the first match will be replaced. See RegExp and String.prototype.replace for further information.

Gumbo
Wow I didn't realize I left off the g. But this works exactly as needed.
Glenn Nelson