Get Off My Lawn
Get Off My Lawn

Reputation: 36351

How to get multiple strings between two other strings

I am trying to find all values between {{ and }} that start with a $ followed by [\w.]+ but doesn't start with a number. This works in getting the value, however, it only gets the last item. What I am looking for, is a list of these items, so in this example I would like my array to contain (based off the example):

['{{I\'m $name and I am $age years old}}', '$name', '$age']

When executed, $name is not included in this array as seen here:

let result = '$welcome: {{I\'m $name and I am $age years old}}'.match(/\{\{.*(\$(?!\d|\.)[\w.]+).*\}\}/)

console.log(result)

Upvotes: 2

Views: 79

Answers (1)

revo
revo

Reputation: 48751

You could try the below regex:

\$[.\w]+(?=[^{}]*})

Live demo

This doesn't really match between {{ and }} but it guarantees that it wouldn't find a match which is outside of braces. It assumes that single, unbalanced braces do not occur in input string.

Another approach would be matching an entire {{...}} block then looking for \$[\w.]+ but if you need to replace them in original input string this wouldn't be an easy option.

Upvotes: 1

Related Questions