Reputation:
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?
Upvotes: 0
Views: 191
Reputation: 655489
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.
Upvotes: 2