Reputation: 3565
I'm trying to replace strings with variables in the same way that Python string formatting works.
The string will be in a similar format to:
string = 'Replace $name$ as well as $age$ and $country$';
And I'd like to have a regex operation that will return and array:
['name', 'age', 'country'] or ['$name$', '$age$', '$country$']
So that I can map it to object keys:
{
name : 'Bob',
age : 50,
country : 'US'
}
I've seen solutions using string concatenation but I need a solution using regex because I have to rely on strings containing these variables.
Upvotes: 1
Views: 364
Reputation: 59232
You can do this:
var string = 'Replace $name$ as well as $age$ and $country$';
var arr = [];
string.replace(/\$(.+?)\$/g, function(m,g1){ arr.push(g1); return m; });
console.log(arr); // desired output
Upvotes: 3