简体   繁体   中英

Javascript replace with reference to matched group?

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?

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

Oh, or you could also:

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

EDIT by Liran H: For six other people including myself, $1 did not work, whereas \\1 did.

您可以使用replace代替gsub

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

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

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM