Javascript RegExp non-capturing groups

capturing-group, javascript, regex, regex-group

Solution

You could use `.replace()` or `.exec()` in a loop to build an Array.

With `.replace()`:

var arr = [];
"#foo#bar".replace(/#([a-zA-Z0-9\-_]*)/g, function(s, g1) {
                                               arr.push(g1);
                                          });

With `.exec()`:

var arr = [],
    s = "#foo#bar",
    re = /#([a-zA-Z0-9\-_]*)/g,
    item;

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

Problem

I am writing a set of RegExps to translate a CSS selector into arrays of ids and classes. For example, I would like '#foo#bar' to return ['foo', 'bar']. I have been trying to achieve this with ``` "#foo#bar".match(/((?:#)[a-zA-Z0-9\-_]*)/g) ``` but it returns ['#foo', '#bar'], when the non-capturing prefix ?: should ignore the # character. Is there a better solution than slicing each one of the returned strings?

Original source