skip-regex: Literal Regular Expression Detector
skip-regex is a lightweight, zero-dependency JavaScript utility designed for the highly accurate and fast detection of literal regular expressions within a string. It is currently at version 1.0.2, with its last release in December 2018, indicating an abandoned or maintenance status rather than active development. The library provides a single function, `skipRegex(source: string, start: number)`, which identifies the end position of a regex given a starting slash. Its key differentiators include a minimal footprint, compatibility across NodeJS, various bundlers, and browsers (including IE9+), and comprehensive TypeScript definitions. This makes it suitable for parsing or code analysis tools that need to distinguish between division operators, comments, and regex literals reliably.
Common errors
-
Module '"skip-regex"' has no default export. Did you mean to use 'import skipRegex = require("skip-regex")'?cause Using `import skipRegex from 'skip-regex'` in a TypeScript project without `esModuleInterop` enabled in `tsconfig.json`.fixEnable `esModuleInterop: true` in your `tsconfig.json` or change the import statement to `import skipRegex = require('skip-regex')`.
Warnings
- gotcha The `start` parameter provided to `skipRegex` *must* point to a forward slash (`/`) character within the `source` string. If `start` points to any other character, the function's behavior is undefined or incorrect.
Install
-
npm install skip-regex -
yarn add skip-regex -
pnpm add skip-regex
Imports
- skipRegex
import skipRegex from 'skip-regex'
- skipRegex
import skipRegex from 'skip-regex' // without esModuleInterop in TypeScript
const skipRegex = require('skip-regex') - skipRegex
import { skipRegex } from 'skip-regex' // Incorrect for default exportimport skipRegex = require('skip-regex')
Quickstart
import skipRegex from 'skip-regex'
const source = 'const foo = bar /.*/g; // this is a regex \n const baz = 10 / 2; // division \n const qux = /* comment */ 5;'
let start = 0;
let currentIndex = 0;
let detectedRegexes = [];
while (currentIndex < source.length) {
start = source.indexOf('/', currentIndex);
if (start === -1) break;
const end = skipRegex(source, start);
if (end > start + 1) {
// Detected as regex if end is greater than start + 1 (meaning it found a regex beyond the initial slash)
const regex = source.slice(start, end);
detectedRegexes.push({ regex, start, end });
currentIndex = end;
} else {
// Not a regex, could be division or comment start.
// skipRegex returns start + 1 if it's not a regex, so we advance past the current slash.
currentIndex = start + 1;
}
}
console.log('Detected Regular Expressions:', detectedRegexes);
// Example output shows how it distinguishes:
// Detected Regular Expressions: [
// { regex: '/.*/g', start: 16, end: 22 }
// ]