Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex replacing multiple groups

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)}'

like image 607
Adrian Buzea Avatar asked Sep 05 '25 02:09

Adrian Buzea


1 Answers

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

like image 105
Wiktor Stribiżew Avatar answered Sep 07 '25 23:09

Wiktor Stribiżew