Lune
Lune

Reputation: 351

how to parse variables using regex

Assume there is a string "aaaa/{helloworld}/dddd/{good}/ccc",
I want to get an array which contains the variables "helloworld" and "good" which are in braces {}.
Is there a simple way to implement this using regex?
Below function doesn't work:

function parseVar(str) {
	var re = /\{.*\}/;	//	new RegExp('{[.*]}');//	/{.*}/;
	var m = str.match(re);
	console.log(m)
	if (m != null) {
		console.log((m));
		console.log(JSON.stringify(m));
	}
}

parseVar("aaaa/{helloworld}/dddd/{good}/ccc");

Upvotes: 0

Views: 335

Answers (1)

michaelmesser
michaelmesser

Reputation: 3726

The global flag (g) allow the regex to find more than one match. .* is greedy, meaning it will take up as many characters as possible but you don't want that so you have to use ? which makes it take up as little characters as possible. It is helpful to use regex101 to test regular expressions.

function parseVar(str) {
  var re = /\{(.*?)\}/g;
  var results = []
  var match = re.exec(str);
  while (match != null) {
    // matched text: match[0]
    // match start: match.index
    // capturing group n: match[n]
    results.push(match[1])
    match = re.exec(str);
  }
  return results
}

var r = parseVar("aaaa/{helloworld}/dddd/{good}/ccc")
document.write(JSON.stringify(r))

Upvotes: 3

Related Questions