Alan Souza
Alan Souza

Reputation: 7795

Does String match glob pattern

I have an array of paths, let's say:

/Users/alansouza/workspace/project/src/js/components/chart/Graph.js

Also I have an entry in a configuration file with additional attributes for this path in a wildcard(glob) format, as in:

{
  '**/*.js': {
    runBabel: true
  }
}

Question: Is there an easy way to validate if the path matches the wildcard expression?

For example:

const matches = Glob.matches(
  '**/*.js',
  '/Users/alansouza/workspace/project/src/js/components/chart/Graph.js'
);

if (matches) {
  //do something
}

FYI: I'm using https://github.com/isaacs/node-glob

Upvotes: 12

Views: 19446

Answers (2)

AJ Richardson
AJ Richardson

Reputation: 6820

As @chiliNUT theorized in a comment, minimatch has this behaviour:

minimatch("file.js", "**/*.js") // true/false
minimatch.match(["file1.js", "file2.js"], "**/*.js") // array of matches

Upvotes: 11

chiliNUT
chiliNUT

Reputation: 19573

You could convert the glob to to a regex with node glob-to-regex and then validate path strings against the regex.
https://www.npmjs.com/package/glob-to-regexp

it looks like node glob is another option.
https://github.com/isaacs/node-glob

And node has its own glob implementation
https://github.com/isaacs/minimatch

My first thought was to see if phpjs had implemented a glob function but it looks like they haven't :(
http://locutus.io/php/

Upvotes: 14

Related Questions