Last active
December 28, 2021 09:05
-
-
Save urugator/f12f7071279b0ab7360aecddd35a788d to your computer and use it in GitHub Desktop.
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
export function escapeRegex(string) { | |
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string | |
} | |
/** | |
* regex`${'escaped'} ${regex`nestable`}` | |
* regex('gi')`withFlags` | |
*/ | |
export function regex(...args) { | |
function _regex(flags, strings, ...values) { | |
strings = strings.raw; // removes the need for double escapes | |
const pattern = values.reduce((pattern, value, index) => { | |
value = value instanceof RegExp ? value.source : escapeRegex(value); | |
return pattern + value + strings[index + 1] | |
}, strings[0]); | |
return RegExp(pattern, flags); | |
} | |
if (Array.isArray(args[0])) { | |
// Used as a template tag | |
return _regex('', ...args); | |
} | |
return (strings, ...values) => _regex(args[0], strings, ...values); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment