The Situation
I have a string that I want to match the same capture group multiple times. I need to be able to get at both matches.
Example Code
var curly = new RegExp("{([a-z0-9]+)}", "gi");
var stringTest = "This is a {test} of my {pattern}";
var matched = curly.exec(stringTest);
console.log(matched);
The Problem
Right now, it only shows the first match, not the second.
JSFiddle Link
/
The Situation
I have a string that I want to match the same capture group multiple times. I need to be able to get at both matches.
Example Code
var curly = new RegExp("{([a-z0-9]+)}", "gi");
var stringTest = "This is a {test} of my {pattern}";
var matched = curly.exec(stringTest);
console.log(matched);
The Problem
Right now, it only shows the first match, not the second.
JSFiddle Link
http://jsfiddle.net/npp8jg39/
Share Improve this question asked Oct 15, 2014 at 21:28 JakeJake 4,23410 gold badges37 silver badges56 bronze badges 2- The asker seems to not will take the time to read the documentation. – Casimir et Hippolyte Commented Oct 15, 2014 at 21:35
- 4 ^ The whole point of this site is for people to ask how to do things they do not understand. Your answer provided no information. – Jake Commented Oct 16, 2014 at 21:59
4 Answers
Reset to default 9Try this:
var curly = /{([a-z0-9]+)}/gi,
stringTest = "This is a {test} of my {pattern}",
matched;
while(matched = curly.exec(stringTest))
console.log(matched);
Normally this is done by the RegExp.exec
method but you know it's convoluted. Everytime I need to use it i have to look up to remember this stateful operation. It's like you need a state monad or something :)
Anyways. In recent JS engines there is this String.matchAll()
which does the same thing in a much sane fashion by returning an iterator object.
var curly = new RegExp("{([a-z0-9]+)}", "gi");
var stringTest = "This is a {test} of my {pattern}";
var matches = [...stringTest.matchAll(curly)];
console.log(matches);
If you need only the capture groups then just map the above result. Let's use Array.from()
this time.
var curly = new RegExp("{([a-z0-9]+)}", "gi");
var stringTest = "This is a {test} of my {pattern}";
var matches = Array.from(stringTest.matchAll(curly), m => m[1]);
console.log(matches);
The exec method must be used in a while loop if you want to treat several results. See the MDN Documentation.
Strings in JavaScript have a match
method - you can use this to match all instances of a regular expression, returned as an array:
stringTest.match(curly);
This will return an array of matches:
> ["{test}", "{pattern}"]
To pull the inner values, you can use substr
:
var arr = stringTest.match(curly);
arr[0] = arr[0].substr(1, arr[0].length - 2);
> "test"
Or to convert the entire array:
for (var i = 0; i < arr.length; i++)
arr[i] = arr[i].substr(1, arr[i].length - 2);
> ["test", "pattern"]