4

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

0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.