Skip to content

Instantly share code, notes, and snippets.

@urugator
Last active December 28, 2021 09:05
Show Gist options
  • Save urugator/f12f7071279b0ab7360aecddd35a788d to your computer and use it in GitHub Desktop.
Save urugator/f12f7071279b0ab7360aecddd35a788d to your computer and use it in GitHub Desktop.
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