Skip to content

Instantly share code, notes, and snippets.

@chriskoelle
Last active July 17, 2020 20:44
Show Gist options
  • Save chriskoelle/885815dbfdfa4d3bf52eab92bb44ff51 to your computer and use it in GitHub Desktop.
Save chriskoelle/885815dbfdfa4d3bf52eab92bb44ff51 to your computer and use it in GitHub Desktop.
Convert a string with asterisk wildcards to a RegExp
/**
* Escape RegExp special characters
*
* @param {string} str String to escape
* @return {string} Escaped string
*/
const escapeRegExp = (str = '') => str.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
/**
* Convert a string with asterisk wildcard characters into a RegExp
*
* @param {string} wc String to convert
* @return {RegExp} Converted RegExp
*
* @example
* wildcardToRegExp('/foo/*'); // /^\/foo\/.*$/
*/
const wildcardToRegExp = (wc = '') => new RegExp(`^${wc.split(/\*+/).map(escapeRegExp).join('.*')}$`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment