Fabrício Matté Fabrício Matté - 2 years ago 97
Javascript Question

Best way to store JS Regex capturing groups in array?

Exactly what title asks. I'll provide some examples while explaining my question.

Test string:

var test = "#foo# #foo# bar #foo#";

Say, I want to extract all text between
s but not

var matches = test.match(/#(.*?)#/g);

as above, it'll store all matches but it'll simply throw away the capturing groups it seems.

var matches2 = /#(.*?)#/g.exec(test);

method apparently returns only the first result's matched string in the position
of the array and my only capturing group of that match in the position

I've exhausted SO, Google and MDN looking for an answer to no avail.

So, my question is, is there any better way to store only the matched capturing groups than looping through it with
and calling
to store the captured groups?

My expected array for the test above should be:

[0] => (string) foo
[1] => (string) foo
[2] => (string) foo

Pure JS and jQuery answers are accepted, extra cookies if you post JSFiddle with
. =]

Answer Source

You can use .exec too like following to build an array

var arr = [],
    s = "#foo# #bar# #test#",
    re = /#(.*?)#/g,

while (item = re.exec(s))

alert(arr.join(' '));‚Äč

Working Fiddle

Found from Here

Well, it still has a loop, if you dont want a loop then I think you have to go with .replace(). In which case the code will be like

var arr = [];
var str = "#foo# #bar# #test#"
str.replace(/#(.*?)#/g, function(s, match) {

Check these lines from MDN DOC which explains your query about howexec updates lastIndex property I think,

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string.

When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download