Skip to content

Instantly share code, notes, and snippets.

@gabrielqmatos88
Forked from donmccurdy/wildcard-to-regexp.js
Created November 4, 2022 01:02
Show Gist options
  • Save gabrielqmatos88/e62d8072ae188d8c83137e9a4539974d to your computer and use it in GitHub Desktop.
Save gabrielqmatos88/e62d8072ae188d8c83137e9a4539974d to your computer and use it in GitHub Desktop.
Wildcard and glob matching in JavaScript.
/**
* 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