Ole
Ole

Reputation: 47038

Create array of all regular expression matches?

I'm attempting to use the package match-all to match CSS selectors and return an array of all of them. This is the code.

const matchAll = require("match-all");

let s = `.u-br, .u-nr {
    blah blah
}

.u-tr {
    blah .blah
}`;
console.log(matchAll(s, /\.-?[_a-zA-Z]+[\w-]*(?=[^{}]*\{)/g).toArray());

When I run it it just logs [], but the regex is correct as can be seen here.

Thoughts? If the package has a bug, is there a simple work around?

Upvotes: 0

Views: 36

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370929

As the documentation shows:

let s = "Hello _World_ and _Mars_";
console.log(matchAll(s, /_([a-z]+)_/gi).toArray());
// => [ "World", "Mars" ]

The resulting array is constructed from the capturing groups. This is what all their examples show. Presumably, if you don't have capturing groups, you could achieve the same thing using the built-in .match:

let s = `.u-br, .u-nr {
    blah blah
}

.u-tr {
    blah .blah
}`;
console.log(s.match(/\.-?[_a-zA-Z]+[\w-]*(?=[^{}]*\{)/g));

So, if you want to use match-all for this, try enclosing the match in a capturing group:

matchAll(s, /(\.-?[_a-zA-Z]+[\w-]*(?=[^{}]*\{))/g).toArray()

Upvotes: 3

Related Questions