I'm trying to replace multiple matched groups based on a regex like this
var paramRegex = /{\s*\[(\w*)\]\s*(\w*)\s*\(([\w\s]*)\)\s*}/i;
// should match {[group1] group2 (group3)}
var emptyParam = '{[]()}';
emptyParam.replace(paramRegex, 'a $1 b $2 c $3');
why does this result in 'a b c' ? Why have the brackets, curly braces and parantheses disappeared ?
I was expecting this to print '{[a]b(c)}'
When replacing, we usually match and capture what we need to keep (to be able to refer to the captured values with backreferences) and only match what you do not need to keep.
In your case, you need to just put the punctuation into the replacement pattern:
.replace(/{\s*\[(\w*)\]\s*(\w*)\s*\(([\w\s]*)\)\s*}/g, "{[a]$1b$2(c)$3)}")
^^ ^ ^ ^ ^^
See the regex demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With