0

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

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

The OP seems to want the results without the curly brackets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.