Skip to content

Instantly share code, notes, and snippets.

@donmccurdy
Last active February 21, 2024 06:49
Show Gist options
  • Select an option

  • Save donmccurdy/6d073ce2c6f3951312dfa45da14a420f to your computer and use it in GitHub Desktop.

Select an option

Save donmccurdy/6d073ce2c6f3951312dfa45da14a420f 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, '\\$&');
}
@KrishnaPG

Copy link
Copy Markdown

Very helpful. Thank you.

@VIKIVIKA

Copy link
Copy Markdown

Thank you so much for this, was struggling for this kind of helper methods. :)

@Jaspervv

Copy link
Copy Markdown

Thanks, this is exactly what I needed!

@charanjit-singh

Copy link
Copy Markdown

anything for python?

@charanjit-singh

Copy link
Copy Markdown

@briwoto

briwoto commented Aug 22, 2022

Copy link
Copy Markdown

This is awesome. Thanks for the amazing helper function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment