简体   繁体   中英

Javascript regex to extract variables

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);

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); 

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM