Reputation: 836
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)}'
Upvotes: 4
Views: 5514
Reputation: 626806
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
Upvotes: 4