Hello.

There is a line:

var tpl = "<div>{title}</div> <div>{description}</div>"; 

and using regular season:

 console.log(tpl.match(/\{[^\}]+\}/g)); 

i pull out of it

 ["{title}", "{description}"] 

and I need the variable names themselves, that is, like this:

 ["title", "description"] 

The question is: can this be done directly in a regular expression, or is it necessary to write a function, after which it will be cut off all this?

  • Yes you can. - RubaXa
  • If you don't know what to do, then do what you know. Regularly, this is a good site for compiling / testing regex101.com - Get

2 answers 2

@Stanislav Dalinin

  1. Open http://javascript.ru/RegExp
  2. http://javascript.ru/regexp/exec

 var tpl = "<div>{title}</div> <div>{description}</div>", regexp = /\{([^\}]+)\}/g, matches, results = []; while (matches = regexp.exec(tpl)) { results.push(matches[1]); } console.log(results); 

 var tpl = "<div>{title}</div> <div>{description}</div>"; var results = (tpl.match(/\{[^\}]+\}/g) || []).map(function (value) { return value.slice(1, -1) }); console.log(results); 

 var tpl = "<div>{title}</div> <div>{description}</div>"; var results = []; tpl.replace(/\{([^\}]+)\}/g, function (_, value) { results.push(value); }); console.log(results); 
     \{([^\}]+)\} 
    • AND? If you just add a group, the result will be the same. - RubaXa
    • And you try. Here, not just a group is added, but braces are moved outside the group's boundaries. Naturally, this line is wrapped in slashes / and do not forget to put g at the end. - Get
    • @RubaXa, here's an example regex101.com/r/xD5aO4/1 - Get
    • Yes please: var tpl = "<div> {title} </ div> <div> {description} </ div>"; tpl.match (/ \ {([^ \}] +) \} / g); // ["{title}", "{description}"] - RubaXa