If I do:
"A first sentence. A second sentence".match(/A\s([^\s]*)\ssentence/g)
this returns:
["A first sentence", "A second sentence"]
And if I use:
RegExp.$1
then I just get the last first parenthesis capture, so "second".
I’d like to get the array ["first","second"]. Is it possible?
You’d need to run it in a loop, and build the collection.
Because the regex is
gglobal, it remembers the position of the last match, and starts from there the next time the regex is used. So the loop will continue until no more matches are found.Inside the loop, we just add the subgroup to the
resultArray.Some people like to use
.replacefor this purpose.We’re not actually doing a string replacement, but rather are just taking advantage of the fact that it repeats the search until no more matches are found.