Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 # (all foos but not bar).

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

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

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

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

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 .exec and calling array.push 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 console.log. =]

like image 722
Fabrício Matté Avatar asked Jun 04 '12 04:06

Fabrício Matté


Video Answer


1 Answers

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

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

while (item = re.exec(s))
    arr.push(item[1]);

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) {
                           arr.push(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).

like image 191
Prasenjit Kumar Nag Avatar answered Sep 21 '22 23:09

Prasenjit Kumar Nag