最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex to extract variables - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Apr 10, 2015 at 12:01 ps0604ps0604 1,07126 gold badges152 silver badges374 bronze badges 3
  • this gives [ "${var1}", "${var2}" ] – atmd Commented Apr 10, 2015 at 12:12
  • Do you need array of variables or array of names of variables, mentioned in the string? – Ruben Kazumov Commented Apr 10, 2015 at 12:12
  • see my example, array of variable names – ps0604 Commented Apr 10, 2015 at 12:15
Add a ment  | 

3 Answers 3

Reset to default 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);

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);
发布评论

评论列表(0)

  1. 暂无评论