Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  76] [ 3]  / answers: 1 / hits: 192068  / 15 Years ago, wed, august 5, 2009, 12:00:00

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?


More From » regex

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

Oh, or you could also:


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

[#98984] Monday, August 3, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
dylondaytond questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, May 7, 20, 00:00, 4 Years ago
;