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?
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);
RegExp objects with quotes: var regex = new RegExp("\\$\\{(\\w+?)\\}", "g")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);
$ and will match 'This is a string with {var1} too. Also anything that ends with a } like 'this is a test}\${([^\s}]+)(?=}). Answer updated.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);
\w+? - can you explain why there is a ? in here? What does that match?? meas as less chars as possible.\w+ ensure at least char?
[ "${var1}", "${var2}" ]