309

I have a string, such as hello _there_. I'd like to replace the two underscores with <div> and </div> respectively, using JavaScript. The output would (therefore) look like hello <div>there</div>. 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| "<div>" + m[1..-2] + "</div>" }

Or be able to reference a matched group, again the way it can be done in ruby:

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

Any ideas or suggestions?

Sinan Taifour
  • 10,521
  • 3
  • 33
  • 30

3 Answers3

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

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
macabeus
  • 4,156
  • 5
  • 37
  • 66
airportyh
  • 21,948
  • 13
  • 58
  • 72
  • 13
    Does Javascript use `$1` instead of `\1`? Would someone provide a link to documentation? – daveloyall Jun 11 '14 at 19:43
  • 3
    `replacementValue` can be a function and it is passed different arguments based on the catch groups? Amazing! – daveloyall Jun 13 '14 at 20:36
  • 6
    i found \1 worked but $1 did NOT although I am using the RegExp variation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references – jsh Oct 01 '15 at 07:55
  • 1
    That's in the regex itself. People are talking about the replacestring. – CalculatorFeline Apr 30 '16 at 00:14
  • 2
    @CalculatorFeline Saying "the regex itself" doesn't identify which one, as someone might be trying to use a regex for the replace. There must be many people trying to do this: `"hello _there_".replace(/_(.*?)_/, /
    \1<\/div>/)`.
    – Stewart Jun 23 '16 at 09:55
  • 6
    Documentation about function replace https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter – Naramsim Jun 07 '18 at 13:44
51

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
Eifion
  • 5,403
  • 2
  • 27
  • 27
25

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>")



Note:

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

Mohamed Allal
  • 17,920
  • 5
  • 94
  • 97