Skip to content

Instantly share code, notes, and snippets.

@urugator
Created June 2, 2022 11:36
Show Gist options
  • Save urugator/6e7fbb6642b9e761c96d2175f63afe15 to your computer and use it in GitHub Desktop.
Save urugator/6e7fbb6642b9e761c96d2175f63afe15 to your computer and use it in GitHub Desktop.
export function escapeRegex(string: string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
export function regex(
strings: TemplateStringsArray,
...values: Array<RegExp | string>
): RegExp;
export function regex(
flags: string,
): (strings: TemplateStringsArray, ...values: Array<RegExp | string>) => RegExp;
/**
* Usage:
* regex`${'escaped'} ${regex`nestable`}`
* regex('gi')`withFlags`
*/
export function regex(...args: any[]) {
function _regex(
flags: string,
strings: TemplateStringsArray,
...values: Array<RegExp | string>
) {
const rawStrings = 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 + rawStrings[index + 1];
}, rawStrings[0]);
return RegExp(pattern, flags);
}
if (Array.isArray(args[0])) {
// Used as a template tag
return _regex(
'',
...(args as [TemplateStringsArray, ...Array<RegExp | string>]),
);
}
return (strings: TemplateStringsArray, ...values: Array<RegExp | string>) =>
_regex(args[0], strings, ...values);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment