Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

Sanitize regex

Ondra Urban5bac0099d7f5
diff --git a/src/key_value_store.js b/src/key_value_store.js
index 1f26f84d5..355177c96 100644
--- a/src/key_value_store.js
+++ b/src/key_value_store.js
@@ -189,7 +189,10 @@ export class KeyValueStore {
* @returns {RegExp}
* @ignore
*/
-export const getFileNameRegexp = key => new RegExp(`^${key}\\.[a-z0-9]+$`);
+export const getFileNameRegexp = (key) => {
+ const safeKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp(`^${safeKey}\\.[a-z0-9]+$`);
+};
/**
* This is a local representation of a key-value store.
diff --git a/test/key_value_store.js b/test/key_value_store.js
index fb907d93b..6df3ebb6f 100644
--- a/test/key_value_store.js
+++ b/test/key_value_store.js
@@ -34,15 +34,18 @@ describe('KeyValueStore', () => {
describe('getFileNameRegexp()', () => {
it('should work', () => {
- const key = 'hello';
+ const key = 'hel.lo';
const filenames = [
- 'hello.txt', // valid
- 'hello.hello.txt',
- 'hello.mp3', // valid
- 'hello....',
- 'hello.hello', // valid
- 'hello.',
- '.hello',
+ 'hel.lo.txt', // valid
+ 'hel.lo.hello.txt',
+ 'hel.lo.mp3', // valid
+ 'hel.lo....',
+ 'hel.lo.hello', // valid
+ 'hello.hel.lo',
+ 'hel.lo.',
+ '.hel.lo',
+ 'hel.lo',
+ 'helXlo.bin',
];
const matched = filenames.reduce((count, name) => (getFileNameRegexp(key).test(name) ? ++count : count), 0);
expect(matched).to.be.eql(3);