version 5.0.0 Regexregex
Runbook

Troubleshooting

Common integration issues and debugging


Objective

This runbook helps you diagnose and resolve the most common issues encountered when integrating ansi-regex into your application, from installation failures through incorrect regex behavior at runtime.


Scope

Covered:

  • Installation and import errors
  • Incorrect or unexpected regex output from ansiRegex()
  • Failures when testing or matching strings against the generated pattern
  • Common environment and version compatibility issues

Not covered:

  • Bugs in the ansi-regex library source code itself (see Escalation)
  • General Node.js environment setup or npm/yarn troubleshooting unrelated to this package
  • Use cases involving binary data or non-ANSI escape sequences

Prerequisites

Before working through this runbook, confirm you have the following in place:

  • Node.js installed (check with node --version)
  • npm or yarn available in your terminal
  • ansi-regex installed in your project (check with npm list ansi-regex)
  • A basic understanding of JavaScript regular expressions
  • Access to a terminal and your project's source files
  • The exact error message or unexpected behavior you are experiencing, noted in full

Steps

Work through these steps in order. Stop when your issue is resolved.


Step 1 — Confirm the package is installed correctly

Run the following command in your project root:

npm list ansi-regex

You should see ansi-regex listed with a version number. If the output shows (empty) or an error, reinstall the package:

npm install ansi-regex

Success looks like: ansi-regex@x.x.x printed in the dependency tree.


Step 2 — Verify your import syntax matches your module system

ansi-regex ships as an ES Module in its current major versions. Using the wrong import style is a frequent cause of TypeError: ansiRegex is not a function or SyntaxError: Cannot use import statement.

For ES Modules (.mjs or "type": "module" in package.json):

import ansiRegex from 'ansi-regex';

For CommonJS projects, use a dynamic import:

const { default: ansiRegex } = await import('ansi-regex');

Success looks like: No import error; typeof ansiRegex returns 'function' when logged.


Step 3 — Confirm the regex is being generated, not reused incorrectly

The ansiRegex() function returns a new RegExp instance each time it is called. Because JavaScript RegExp objects with the g (global) flag maintain internal state (lastIndex), reusing a single instance across multiple calls can produce inconsistent results.

Do not do this:

const pattern = ansiRegex(); // created once
const results = [];
for (const line of lines) {
  results.push(pattern.test(line)); // lastIndex state causes skipped matches
}

Do this instead:

for (const line of lines) {
  const pattern = ansiRegex(); // fresh instance per use
  results.push(pattern.test(line));
}

Alternatively, reset lastIndex manually after each use:

const pattern = ansiRegex();
for (const line of lines) {
  pattern.lastIndex = 0;
  results.push(pattern.test(line));
}

Success looks like: Consistent match results across all lines in your dataset.


Step 4 — Check that your input string actually contains ANSI escape codes

If pattern.test(str) returns false when you expect true, confirm the string genuinely contains ANSI sequences. Some terminals or logging libraries strip escape codes before your code sees them.

Log the raw string representation:

console.log(JSON.stringify(myString));
// ANSI codes appear as \u001B[ or \x1B[ sequences
// e.g. "\u001B[31mHello\u001B[0m"

If no \u001B (ESC) characters appear, the ANSI codes were stripped upstream and the regex behaving correctly — your input is already clean.

Success looks like: \u001B[ sequences visible in the JSON.stringify output when codes are expected.


Step 5 — Validate the onlyFirst option if only the first match matters

ansiRegex() accepts an options object. Passing { onlyFirst: true } generates a pattern without the global flag, so it stops after the first match. Ensure you are passing this option intentionally:

// Matches ALL ANSI sequences in the string
const globalPattern = ansiRegex();

// Matches only the FIRST ANSI sequence
const firstOnlyPattern = ansiRegex({ onlyFirst: true });

const sample = '\u001B[31mRed\u001B[0m and \u001B[32mGreen\u001B[0m';
console.log(sample.match(globalPattern));    // array of all matches
console.log(sample.match(firstOnlyPattern)); // array with one match

Success looks like: The number of matches returned aligns with the option you passed.


Step 6 — Isolate the issue with a minimal reproduction

If none of the above steps resolved the issue, reduce your code to the smallest snippet that reproduces the problem:

import ansiRegex from 'ansi-regex';

const pattern = ansiRegex();
const testString = '\u001B[4mUnderline\u001B[0m';

console.log('Pattern:', pattern);
console.log('Test result:', pattern.test(testString));
console.log('Match result:', testString.match(ansiRegex()));

Run this in isolation (node repro.mjs). If it works correctly, the issue lies in how your application constructs or passes the string — not in ansi-regex itself.

Success looks like: Either the bug reproduces cleanly (useful for escalation) or works correctly (narrowing the problem to your application code).


Verification

After applying fixes, confirm the integration is working as expected using the following checks:

  1. Import resolves without error — Running your entry file produces no SyntaxError, TypeError, or ERR_REQUIRE_ESM on startup.

  2. ansiRegex() returns a RegExp — Add a temporary assertion:

    import ansiRegex from 'ansi-regex';
    console.assert(ansiRegex() instanceof RegExp, 'ansiRegex must return a RegExp');
    

    No assertion failure should appear.

  3. Known ANSI string matches — Run a quick smoke test:

    const hasAnsi = ansiRegex().test('\u001B[31mError\u001B[0m');
    console.assert(hasAnsi === true, 'Should detect ANSI codes');
    
    const noAnsi = ansiRegex().test('Plain text');
    console.assert(noAnsi === false, 'Should not match plain text');
    

    Both assertions must pass silently.

  4. Match extraction returns expected results — Verify that String.prototype.replace with the pattern removes all escape codes:

    const cleaned = '\u001B[31mHello\u001B[0m'.replace(ansiRegex(), '');
    console.assert(cleaned === 'Hello', `Expected 'Hello', got '${cleaned}'`);
    

All four checks passing indicates the integration is functioning correctly.


Rollback

Because ansi-regex is a read-only utility library that generates regular expressions without side effects, most actions in this runbook involve no persistent changes. However, if you modified your project to work around a suspected issue, reverse those changes as follows:

  • If you changed your package.json "type" field (e.g., added or removed "module"), revert the file to its previous state and run npm install to re-sync the lockfile.

  • If you downgraded or upgraded ansi-regex to test compatibility, restore the original version:

    npm install ansi-regex@<original-version>
    

    Replace <original-version> with the version pinned in your original package-lock.json or yarn.lock before the change.

  • If you added a dynamic import() wrapper to work around ESM issues and it is no longer needed, remove it and restore the original static import statement.

  • Restore from version control if multiple changes were made and the original state is unclear:

    git checkout -- package.json package-lock.json
    npm install
    

Escalation

If you have completed all steps in this runbook and the issue persists, escalate as follows:

1. Check for existing known issues

Search the ansi-regex GitHub issue tracker before filing a new report. The issue may already be reported and have a workaround.

2. File a bug report

Open an issue on the official ansi-regex repository. Include all of the following information to enable a fast resolution:

  • ansi-regex version (npm list ansi-regex)
  • Node.js version (node --version)
  • Operating system and version
  • Module system in use (CommonJS or ESM)
  • Minimal reproduction script (from Step 6 of this runbook)
  • Full error output or unexpected output, copied verbatim
  • Steps you have already tried from this runbook

3. Internal escalation

If your organization has an internal developer platform or shared libraries team, share the same details listed above. Indicate that the issue was not resolvable using the standard troubleshooting runbook and attach the minimal reproduction script.