skip-regex: Literal Regular Expression Detector

1.0.2 · abandoned · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to iterate through a string to find and extract all literal regular expressions using `skipRegex`, differentiating them from division operators or comment starts.

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 }
// ]

view raw JSON →