Skip to content

Instantly share code, notes, and snippets.

@axetroy
Last active November 9, 2023 17:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axetroy/7963977650a7dd240abbd72e10cfae60 to your computer and use it in GitHub Desktop.
Save axetroy/7963977650a7dd240abbd72e10cfae60 to your computer and use it in GitHub Desktop.
Glob string transform to javascript RegExp
function glob2regexp(glob) {
const prefix = "^/?(.*/)*";
const suffix = "$";
const content = glob
.replace(/\./g, ".")
.replace(/\*{2,}/, "**")
.replace(/\*{1,}\/?/g, function (match, b, c, d) {
const matchSlash = match[match.length - 1] === "/";
match = !matchSlash ? match : match.substr(0, match.length - 1);
if (match === "**") {
return matchSlash ? "((.*)/)*" : "(.*)";
} else {
return matchSlash ? "(.+)" + "/" : "(.+)";
}
});
const globRegExpString = prefix + content + suffix;
const reg = new RegExp(globRegExpString);
return reg;
}
console.log(glob2regexp("views-*/**/*.js").test("views-admin/hello/123123/test.js"));
// true
console.log(glob2regexp("views-*/**/*.js").test("views-admin/test.js"));
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment