Skip to content

Commit 598952e

Browse files
authored
feat: create injectable regex utility function (#536)
This PR introduces a new utility function, `createInjectableRegExp()`, that converts any regex into an "injectable" version by removing its leading `^` and trailing `$` anchors. This is useful when you need to embed an existing pattern, which was originally designed to match a whole string, inside another regex to match it as a substring. Thanks to this, we can replace [APIFY_PROXY_VALUE_REGEX](https://github.com/apify/apify-shared-js/blob/master/packages/consts/src/regexs.ts#L51) with [REGEX_STR_USERNAME_VALUE](https://github.com/apify/apify-proxy/blob/develop/src/proxy_utils.ts#L20) in Apify proxy and solve this issue apify/apify-proxy#1079. The function was created in Apify shared repo, so it can be used in other places.
1 parent 916d84d commit 598952e

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

packages/utilities/src/utilities.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,3 +429,10 @@ export async function timeoutPromise<T>(promise: Promise<T>, timeoutMillis: numb
429429
timeout = setTimeout(() => callback(new Error(errorMessage)), timeoutMillis) as unknown as number;
430430
});
431431
}
432+
433+
/**
434+
* Removes the leading ^ and trailing $ from regex
435+
*/
436+
export function createInjectableRegExp(regex: RegExp) {
437+
return new RegExp(regex.source.replace(/^\^|\$$/g, ''));
438+
}

test/utilities.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,3 +398,21 @@ describe('BetterSetInterval', () => {
398398
expect(fn).toHaveBeenCalledTimes(4);
399399
});
400400
});
401+
402+
describe('createInjectableRegExp()', () => {
403+
it('works with leading ^ and trailing $', () => {
404+
expect(utils.createInjectableRegExp(/^[\w._~]+$/)).toStrictEqual(/[\w._~]+/);
405+
});
406+
407+
it('works with leading ^', () => {
408+
expect(utils.createInjectableRegExp(/^[\w._~]+/)).toStrictEqual(/[\w._~]+/);
409+
});
410+
411+
it('works with trailing $', () => {
412+
expect(utils.createInjectableRegExp(/[\w._~]+$/)).toStrictEqual(/[\w._~]+/);
413+
});
414+
415+
it('works when regex is already injectable', () => {
416+
expect(utils.createInjectableRegExp(/[\w._~]+/)).toStrictEqual(/[\w._~]+/);
417+
});
418+
});

0 commit comments

Comments
 (0)