1

I have a string in Javascript that contains variables with the format ${var-name}. For example:

'This is a string with ${var1} and ${var2}'

I need to get these variables in an array: ['var1','var2'].

Is this possible with regex?

ps0604
  • 1,227
  • 23
  • 133
  • 330

3 Answers3

4

Have a try with:

/\$\{(\w+?)\}/

Running example, many thanks to @RGraham :

var regex = new RegExp(/\$\{(\w+?)\}/g),
    text = "This is a string with ${var1} and ${var2} and {var3}",
    result,
    out = [];
while(result = regex.exec(text)) {
    out.push(result[1]);
}
console.log(out);
Toto
  • 89,455
  • 62
  • 89
  • 125
  • @RGraham: You're right, I'm not used to regex javascript. – Toto Apr 10 '15 at 12:20
  • You were close enough: If you want to use variables in a Regex, you have the use the `RegExp` objects with quotes: `var regex = new RegExp("\\$\\{(\\w+?)\\}", "g")` – nils Apr 10 '15 at 12:32
  • If you're not leveraging the [benefits](https://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun) of `exec()`, then stick to String's `match()` as it's a lot more efficient. – thdoan Jul 02 '23 at 08:14
3

This regex - \${([^\s}]+)(?=}) - should work.

Explanation:

  • \${ - Match literal ${
  • ([^\s}]+) - A capture group that will match 1 or more character that are not whitespace or literal }.
  • (?=}) - A positive look-ahead that will check if we finally matched a literal }.

Here is sample code:

var re = /\${([^\s}]+)(?=})/g; 
var str = 'This is a string with ${var1} and ${var2} and {var3}';
var arr = [];
 
while ((m = re.exec(str)) !== null) {
    arr.push(m[1]);
}

alert(arr);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Nice to see an explanation of Regex for a change! However, this doesn't take into account the `$` and will match `'This is a string with {var1}` too. Also anything that ends with a `}` like `'this is a test}` – CodingIntrigue Apr 10 '15 at 13:05
  • 1
    @RGraham: I guess these cases are not expected. If they are, then it is really easy to fix by `\${([^\s}]+)(?=})`. Answer updated. – Wiktor Stribiżew Apr 10 '15 at 13:09
0
var str = 'This is a string with ${var1} and ${var2}';

var re = /\$\{(\w+?)\}/g;
var arr = [];
var match;
while (match = re.exec(str)) {
  arr.push(match[1]);
}

console.log(arr);
alsotang
  • 1,520
  • 1
  • 13
  • 15