version 5.0.0 Regexregex
Tutorial

Getting Started

Installation and first API call


Overview
Getting Started with ansi-regex Installation & First API Call Workflow Start Open Terminal / CLI in your project directory Node.js installed? (v12+ recommended) No Install Node.js from nodejs.org Yes Install ansi-regex npm install ansi-regex Import module in your file const ansiRegex = require('ansi-regex'); Call ansiRegex() to get pattern const regex = ansiRegex(); Use regex to match ANSI codes Also works with: yarn add ansi-regex str.match(regex) regex.test(str) str.replace(regex,'') Legend Start / End Action Step Decision

This page walks you through installing ansi-regex and making your first API call to generate and use an ANSI escape code regular expression. ansi-regex provides a single function that returns a pre-built RegExp object capable of matching ANSI escape sequences in strings or file content. Whether you need to strip terminal formatting from output or detect styled text, this library gives you a reliable, battle-tested pattern without writing the complex regex yourself. By the end of this guide, you will have the library installed and a working example that detects ANSI codes in a string.


Prerequisites

Before you begin, make sure you have the following in place:

  • Node.js installed on your machine (any actively maintained LTS version is recommended)
  • npm or yarn available in your terminal for package installation
  • A JavaScript or Node.js project already initialized (run npm init -y if you are starting fresh)
  • Basic familiarity with require() or ES module imports in Node.js

Quick start
  1. Install the package via npm:
    npm install ansi-regex
    
  2. Import the library in your script:
    const ansiRegex = require('ansi-regex');
    
  3. Call the function to get a ready-to-use RegExp:
    const regex = ansiRegex();
    
  4. Use the regex to test or match a string containing ANSI codes:
    console.log(regex.test('\u001B[4mHello\u001B[0m')); // true
    

Steps

Step 1 — Install the package

Run the following command in the root of your project directory:

npm install ansi-regex

You should see ansi-regex appear in your package.json under dependencies. This confirms the package is available for import.


Step 2 — Import ansi-regex

In your JavaScript file, require the library:

'use strict';
const ansiRegex = require('ansi-regex');

ansiRegex is a function — you must call it to retrieve the RegExp object. It is not the regex itself.


Step 3 — Generate the regular expression

Call ansiRegex() with no arguments to get a global RegExp that matches all ANSI escape sequences:

const regex = ansiRegex();

The returned object is a standard JavaScript RegExp with the g (global) flag set, so it will find all occurrences in a string — not just the first one.


Step 4 — Test or match a string

Now use the regex against any string that may contain ANSI escape codes:

const hasAnsi = regex.test('\u001B[4mUnderlined text\u001B[0m');
console.log(hasAnsi); // true

If the string contains no ANSI sequences, test() returns false. Because the regex is global, if you plan to reuse the same instance across multiple calls, be aware that JavaScript's RegExp.prototype.test() advances lastIndex on a global regex — call ansiRegex() again or reset regex.lastIndex = 0 between reuses.


Examples

Example 1 — Check whether a string contains ANSI codes

Use .test() to get a boolean result.

'use strict';
const ansiRegex = require('ansi-regex');

const regex = ansiRegex();
const input = '\u001B[31mError:\u001B[0m something went wrong';

console.log(regex.test(input));

Expected output:

true

Example 2 — Extract all ANSI escape sequences from a string

Use .match() on the string to collect every matched sequence. Because the regex has the g flag, all matches are returned as an array.

'use strict';
const ansiRegex = require('ansi-regex');

const input = '\u001B[4mHello\u001B[0m, \u001B[31mworld\u001B[0m!';
const matches = input.match(ansiRegex());

console.log(matches);

Expected output:

[ '\u001B[4m', '\u001B[0m', '\u001B[31m', '\u001B[0m' ]

Example 3 — Strip ANSI codes from a string

Use .replace() to remove all escape sequences and retrieve plain text.

'use strict';
const ansiRegex = require('ansi-regex');

const styled = '\u001B[1mBold\u001B[0m and \u001B[4munderlined\u001B[0m';
const plain = styled.replace(ansiRegex(), '');

console.log(plain);

Expected output:

Bold and underlined

Troubleshooting

Issue: require('ansi-regex') throws Cannot find module 'ansi-regex'

  • Likely cause: The package was not installed, or installation did not complete successfully.
  • Fix: Run npm install ansi-regex in your project root and verify the package appears in node_modules/ and package.json.

Issue: regex.test() always returns false after the first call

  • Likely cause: You are reusing the same RegExp instance across multiple .test() calls. Because the regex is compiled with the g flag, JavaScript advances lastIndex after each match, causing subsequent tests on different strings to start from the wrong position.
  • Fix: Either call ansiRegex() each time you need a fresh regex, or manually reset regex.lastIndex = 0 before each test.

Issue: .match() returns null on a string that visually appears to have color

  • Likely cause: The string may not actually contain raw ANSI escape bytes. Some environments pre-strip escape codes before your code receives the string, or the string was serialized/logged in a way that converted escape characters to literal text (e.g., \\u001B instead of \u001B).
  • Fix: Inspect the raw string value using JSON.stringify(input) and confirm that real escape characters (\u001B or \u009B) are present, not escaped representations of them.

Issue: The regex matches more characters than expected

  • Likely cause: The g (global) flag causes the regex to match all occurrences. If you only need to find the first match, use the returned RegExp with .exec() and check the first result, or use String.prototype.match() without the global flag by creating a non-global copy.
  • Fix: For single-match behavior, use regex.exec(input) and read result[0], or construct your own RegExp from the pattern without the g flag.