cgsd cgsd - 8 days ago 6
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
${
and
}
.

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

Answer

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 : \${(.*?)}.