简体   繁体   中英

Javascript replace with part of match?

I'm looking over replace() examples and I'm not exactly sure the best way to do this:

Say I have a string something like

{G}{J}{L}...

What's the best way to use string.replace() to change the inner and outer brackets but leave the letter inside them? Do I need to do separate matches for the outer and inner brackets or is it possible/faster to do it in a single statement?

I see that $ can get the whole match and I guess I could remove the first and last characters and replace them after but that seems slow.

> "{G}{J}{L}".replace(/{(.)}/g,"$1")
"GJL"

Is this what you're after? Or maybe this?

> "{G}{J}{L}".replace(/{(.)}/g,"[$1]")
"[G][J][L]"

One pretty straightforward way is to just perform the replacements separately, and the performance difference should be negligible unless your strings are huge:

var string = "{G}{J}{L}";
string = string.replace(/\{/g, "<").replace(/}/g, ">")

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