cgsd cgsd - 1 year ago 133
Javascript Question

Extract content inside curly braces using javascript regex

Let's say I have a string

let str = 'foo ${bar}baz ${foobar}'

I want to extract all the elements between the

So I would want to return
['bar', 'foobar']
, ideally using
function in Javascript. Any brilliant regex wizards out there willing to lend a hand?

Answer Source

I would do something like this if a Regex is not a real constraint :

let str = 'foo ${bar}baz ${foobar}'

console.log(str.split("${").slice(1).map(item => item.split("}")[0]))
// Outputs : ["bar", "foobar"]

Otherwise, here is a Regex that might fit your need : \${(.*?)}.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download