Glob to Regex

1.2.0 · active · verified Sun Apr 19

The `glob-to-regex.js` library, currently stable at version 1.2.0, provides a lightweight and performant solution for converting shell-style glob patterns into native JavaScript `RegExp` objects. It is actively maintained, with recent feature releases in late 2025, demonstrating a consistent development cadence. Key differentiators include its focus on performance by leveraging V8's optimized regex engine for matching, the provision of both a direct `toRegex` function for `RegExp` generation and a `toMatcher` utility for predicate functions, and comprehensive support for various glob features including extended globbing (enabled via an option since v1.2.0) and character classes. The package ships with first-class TypeScript types, ensuring a robust developer experience. Unlike some alternatives, it explicitly anchors all generated regular expressions, which is crucial for precise full-path matching, though this can be a behavioral nuance for new users. Its small footprint makes it suitable for environments where bundle size is a concern.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates converting simple and complex glob patterns to regular expressions, using the matcher utility, and highlights key behaviors like extended glob support and implicit anchoring.

import {toRegex, toMatcher} from 'glob-to-regex.js';

// Build a RegExp from a glob
const re = toRegex('src/**/test.ts');
console.log(`'src/a/b/test.ts' matches 'src/**/test.ts': ${re.test('src/a/b/test.ts')}`); // true
console.log(`'src/test.ts' matches 'src/**/test.ts': ${re.test('src/test.ts')}`);     // true
console.log(`'src/test.tsx' matches 'src/**/test.ts': ${re.test('src/test.tsx')}`);    // false

// Build a predicate function from a pattern or an array of patterns
const match = toMatcher(['**/*.ts', '!**/*.d.ts']); // negative patterns are not special; use a RegExp if needed
console.log(`'index.ts' matches ['**/*.ts', '!**/*.d.ts']: ${match('index.ts')}`);    // true
console.log(`'types.d.ts' matches ['**/*.ts', '!**/*.d.ts']: ${match('types.d.ts')}`);  // true (negation is not parsed specially)

// Demonstrate extended globs (requires option)
const reExt = toRegex('file.@(jpg|png|gif)', {extglob: true});
console.log(`'file.jpg' matches 'file.@(jpg|png|gif)' with extglob: ${reExt.test('file.jpg')}`); // true
console.log(`'file.txt' matches 'file.@(jpg|png|gif)' with extglob: ${reExt.test('file.txt')}`); // false

// Demonstrate anchored regex behavior
const reAnchored = toRegex('*.js');
console.log(`'my-file.js' matches '*.js': ${reAnchored.test('my-file.js')}`); // true
console.log(`'path/to/my-file.js' matches '*.js': ${reAnchored.test('path/to/my-file.js')}`); // false (due to implicit anchoring) 

view raw JSON →