Last active
November 9, 2023 17:50
-
-
Save axetroy/7963977650a7dd240abbd72e10cfae60 to your computer and use it in GitHub Desktop.
Glob string transform to javascript RegExp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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