Last active
February 21, 2024 06:49
-
-
Save donmccurdy/6d073ce2c6f3951312dfa45da14a420f to your computer and use it in GitHub Desktop.
Wildcard and glob matching in JavaScript.
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
/** | |
* Creates a RegExp from the given string, converting asterisks to .* expressions, | |
* and escaping all other characters. | |
*/ | |
function wildcardToRegExp (s) { | |
return new RegExp('^' + s.split(/\*+/).map(regExpEscape).join('.*') + '$'); | |
} | |
/** | |
* RegExp-escapes all characters in the given string. | |
*/ | |
function regExpEscape (s) { | |
return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome. Thanks for the amazing helper function