Last active
July 17, 2020 20:44
-
-
Save chriskoelle/885815dbfdfa4d3bf52eab92bb44ff51 to your computer and use it in GitHub Desktop.
Convert a string with asterisk wildcards to a RegExp
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
/** | |
* 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