Javascript replace with reference to matched group?


Javascript replace with reference to matched group?

I have a string, such as hello _there_. I’d like to replace the two underscores with


respectively, using JavaScript. The output would (therefore) look like hello


. The string might contain multiple pairs of underscores.
What I am looking for is a way to either run a function on each match, the way Ruby does it:
“hello _there_”.gsub(/_.*?_/) { |m| “

” + m[1..-2] + “

” }

Or be able to reference a matched group, again the way it can be done in ruby:
“hello _there_”.gsub(/_(.*?)_/, “



Any ideas or suggestions?


Solution 1:

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")

Solution 2:

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")

Solution 3:

For the replacement string and the replacement pattern as specified by $.
here a resume:

enter image description here

link to doc : here

"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")


If you want to have a $ in the replacement string use $$. Same as with vscode snippet system.