0

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?

1
  • 1
    Funny, the output you should have gotten with that regex is "_ is a sentence." Commented Aug 3, 2010 at 18:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.