Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Match globs in browser-based JavaScript

In browser-based JavaScript, is it possible to perform glob pattern matching?

For illustrative purposes only, I mean a glob like this: **/*.{eot,otf,ttf,woff,woff2}, which could be matched against a URL. Or perhaps something similar to match against a list of files, etc.

To reiterate, this is in the browser: so no Node, npm packages, SPA libraries, etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are different solutions – but you will probably have to use a npm library.

For example glob-to-regexp (npm) – which has over 20mio weekly downloads (Nov 2023)

glob-to-regexp will convert a glob pattern expression into a regular expression:

var globToRegExp = require('glob-to-regexp');
var re = globToRegExp("**/*.{eot,otf,ttf,woff,woff2}");
re.test("/this/is/an/example/a.woff"); // true

you could also convert a regexp into a string on the server or during build time:

var globToRegexp = require("glob-to-regexp")
const re = globToRegexp("**/*.{eot,otf,ttf,woff,woff2}");
const reString = re.toString();
// -> "/^.*\\/.*\\.\\{eot\\,otf\\,ttf\\,woff\\,woff2\\}$/"

in the browser you can use the string of the regexp and turn it back into a regular expression:

const re = new RegExp("/^.*\\/.*\\.\\{eot\\,otf\\,ttf\\,woff\\,woff2\\}$/");
re.test("/this/is/an/example/a.woff"); // true
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading