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?

3
  • this gives [ "${var1}", "${var2}" ] Commented Apr 10, 2015 at 12:12
  • Do you need array of variables or array of names of variables, mentioned in the string? Commented Apr 10, 2015 at 12:12
  • see my example, array of variable names Commented Apr 10, 2015 at 12:15

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

@RGraham: You're right, I'm not used to regex javascript.
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")
If you're not leveraging the benefits of exec(), then stick to String's match() as it's a lot more efficient.
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);

2 Comments

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}
@RGraham: I guess these cases are not expected. If they are, then it is really easy to fix by \${([^\s}]+)(?=}). Answer updated.
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);

5 Comments

I don't need to replace the variables, just to load them in an array
\w+? - can you explain why there is a ? in here? What does that match?
? meas as less chars as possible.
But doesn't \w+ ensure at least char?
@alsotang, when you post code to answer a question, you should explain what the OP did wrong and what you did to fix it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.