diff --git a/src/__tests__/index.test.ts b/src/__tests__/index.test.ts index edd87e7..ab5809f 100644 --- a/src/__tests__/index.test.ts +++ b/src/__tests__/index.test.ts @@ -11,6 +11,13 @@ it('should build regexes properly', () => { \s+ `).toStrictEqual(/\d+\s+/); + expect(regex` + // Here's an interpolation + ${/\d+\s/g} + /* Here's a nested regex call */ + ${regex`.*`} + `).toStrictEqual(/\d+\s.*/); + expect(regex` // Here's an interpolation @@ -54,5 +61,5 @@ it('should build regexes properly', () => { May not match everything because extensions are (mostly) letters */ [a-z0-9](?:[a-z0-9-]*[a-z0-9])? - ${'g'}`).toStrictEqual(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z\d!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z\d](?:[a-z\d-]*[a-z\d])?\.)+[a-z\d](?:[a-z\d-]*[a-z\d])?/g); + ${'g'}`).toStrictEqual(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g); }); diff --git a/src/index.ts b/src/index.ts index 41e4c7a..d633d77 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,11 +20,11 @@ */ /** - * Clean a string (remove comments, whitespace, extra stuff in other template literals and such) + * Clean a string (remove comments, whitespace, etc.) * @param piece the string to clean - * @returns string + * @returns {string} th cleaned string */ -export function clean(piece: string) { +export function clean(piece: string): string { // Funny how we don't use our own functions to build our own regexes return piece // Get rid of any escaped (`) tildes @@ -37,13 +37,28 @@ export function clean(piece: string) { .replace(/\n\s*/g, ''); } -export function regex({raw}: TemplateStringsArray, ...interpolations: string[]) { - const flags: string | undefined = raw[raw.length - 1] ? undefined : interpolations.pop(); +/** + * Parse an object to make it embeddable within an object + * @param interpol the interpolation to parse5 + * @returns {string} The stringified regex + */ +function parse(interpol: any): string { + return interpol instanceof RegExp ? interpol.source : [interpol].join(); +} + +/** + * Convert a string to a regex + * @param param0 The template strings array + * @param interpolations the interpolations + * @returns {RegExp} The parsed regex + */ +export function regex({raw}: TemplateStringsArray, ...interpolations: any[]): RegExp { + const flags = raw[raw.length - 1] ? '' : parse(interpolations.pop()); /* eslint-disable-next-line unicorn/no-array-reduce */ return new RegExp(interpolations.reduce( (regexp, insert, index) => { - return `${regexp}${insert}${clean(raw[index + 1])}`; + return `${parse(regexp)}${parse(insert)}${clean(raw[index + 1])}`; }, clean(raw[0]) - ), flags); + ) as string, flags); }