Reputation: 21
I'm looking for a regex pattern which will match only one set of curly brackets.
Basically I have a object like this: {Hello: '${name}'}
and I want a pattern which will only replace the brackets around the variable and not all. The output should be something like: {Hello: 'name'}
and the value of name can then be inserted. This is the regex that I created: (\$\{|\})
but it is replacing even the last bracket and outputs something like this: {Hello: 'name'
Can anyone help me figure out where I'm going wrong?
Upvotes: 1
Views: 68
Reputation: 626950
You can use
.replace(/\$\{(\w+)}/g, '$1')
Alternatively:
.replace(/\$\{([^{}]+)}/g, '$1')
See the regex demo. Details:
\$\{
- ${
string(\w+)
- Group 1: one or more letters/digits/underscores[^{}]+
- one or more chars other than {
and }
}
- a }
char.See the JavaScript demo:
console.log("{Hello: '${name}'}".replace(/\$\{(\w+)}/g, '$1'))
Upvotes: 2