Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@KrishnaPG KrishnaPG commented Jun 25, 2020

Very helpful. Thank you.

@VIKIVIKA

This comment has been minimized.

Copy link

@VIKIVIKA VIKIVIKA commented Dec 23, 2020

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

@Jaspervv

This comment has been minimized.

Copy link

@Jaspervv Jaspervv commented Mar 16, 2021

Thanks, this is exactly what I needed!

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