---
title: Examples
product: version-5-0-0-regex
doc_type: guide
version: v3.0.1
source: git2docs (code-derived, validation-filtered)
canonical: https://git2docs.com/source2books/docs/version-5-0-0-regex/ansi-regular-expression/examples
---

# Examples

_Real-world code examples_

## Overview

This page provides practical, runnable code examples for integrating `ansi-regex` into your Node.js applications. You'll see how to generate the ANSI escape code regular expression, use it to detect ANSI sequences in strings, and apply it to real-world scenarios like stripping color codes from terminal output. These examples build on one another, so reading them in order will give you a solid foundation for using the library effectively.

## Prerequisites

Before working through these examples, make sure you have the following:

- **Node.js** installed (any actively maintained LTS version)
- **npm** or **yarn** available in your terminal
- Basic familiarity with JavaScript `RegExp` methods (`.test()`, `.match()`, `.replace()`)
- `ansi-regex` installed in your project (see the Installation section below)

## Installation

1. Navigate to your project directory in your terminal.

2. Install `ansi-regex` using npm:

```bash
npm install ansi-regex
```

Or, if you prefer yarn:

```bash
yarn add ansi-regex
```

3. Verify the installation by checking your `node_modules` directory or running:

```bash
node -e "require('ansi-regex'); console.log('ansi-regex installed successfully')"
```

## Configuration

`ansi-regex` exposes a single factory function that you call with no arguments. It has no external configuration options or constructor parameters — calling the function always returns a freshly constructed `RegExp` object with the global (`g`) flag set.

| Aspect | Value | Notes |
|---|---|---|
| **Function signature** | `ansiRegex()` | No parameters accepted |
| **Return type** | `RegExp` | A new instance on every call |
| **Flags** | `g` (global) | Matches all occurrences in a string, not just the first |
| **Statefulness** | Stateless factory | Each call returns a fresh regex; safe to reuse across calls |

Because a new `RegExp` instance is returned on every invocation, you avoid the pitfall of the global flag's `lastIndex` state carrying over between unrelated operations. If you plan to call `.test()` or `.exec()` in a loop against the same string, always call `ansiRegex()` fresh rather than reusing a single instance.

## Usage

Import the library and call `ansiRegex()` to obtain the regular expression, then use standard JavaScript `RegExp` methods against your strings.

**Import the module**

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

**Generate the regex**

```js
const regex = ansiRegex();
// regex is a RegExp with the global flag
```

**Test whether a string contains ANSI codes**

Use `.test()` when you only need a boolean answer:

```js
const hasAnsi = ansiRegex().test('\u001B[4mUnderline\u001B[0m');
// true
```

**Find all ANSI sequences in a string**

Use `.match()` to collect every escape sequence present:

```js
const sequences = '\u001B[4mHello\u001B[0m'.match(ansiRegex());
// ['\u001B[4m', '\u001B[0m']
```

**Strip ANSI codes from a string**

Replace every matched sequence with an empty string to get plain text:

```js
const plain = '\u001B[4mHello\u001B[0m'.replace(ansiRegex(), '');
// 'Hello'
```

## Examples

### Example 1 — Detecting ANSI escape codes

Check whether a string coming from a terminal or log file contains any ANSI sequences before processing it.

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

const rawOutput = '\u001B[32mSUCCESS\u001B[0m: build complete';

if (ansiRegex().test(rawOutput)) {
  console.log('String contains ANSI escape codes.');
} else {
  console.log('String is plain text.');
}
```

**Expected output:**
```
String contains ANSI escape codes.
```

---

### Example 2 — Extracting all ANSI sequences from a string

Collect every escape sequence present so you can inspect or log them.

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

const coloredText = '\u001B[1m\u001B[33mWarning:\u001B[0m disk usage above 90%';
const sequences = coloredText.match(ansiRegex());

console.log(sequences);
```

**Expected output:**
```
[ '\u001B[1m', '\u001B[33m', '\u001B[0m' ]
```

---

### Example 3 — Stripping ANSI codes to produce plain text

Remove all escape sequences before writing output to a plain-text log file or comparing strings in tests.

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

const styledMessage = '\u001B[4m\u001B[31mERROR\u001B[0m: file not found';
const plainMessage = styledMessage.replace(ansiRegex(), '');

console.log(plainMessage);
```

**Expected output:**
```
ERROR: file not found
```

---

### Example 4 — Processing multiple strings safely

Because `ansiRegex()` returns a fresh instance each time, you can safely test multiple strings without worrying about `lastIndex` state.

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

const lines = [
  '\u001B[32mOK\u001B[0m',
  'No ANSI here',
  '\u001B[31mFAIL\u001B[0m'
];

lines.forEach(line => {
  // Call ansiRegex() inside the loop for a fresh regex each iteration
  const stripped = line.replace(ansiRegex(), '');
  console.log(stripped);
});
```

**Expected output:**
```
OK
No ANSI here
FAIL
```

## Troubleshooting

### Issue 1 — `.test()` returns `false` for every string after the first match

**Symptom:** You store the result of `ansiRegex()` in a variable and call `.test()` on it multiple times; after the first `true` result, subsequent calls return `false` even on strings that clearly contain ANSI codes.

**Cause:** JavaScript `RegExp` objects with the global (`g`) flag maintain a `lastIndex` property. After a successful `.test()` call, `lastIndex` advances to the position after the match. On the next call against a different string, the search starts from that stale offset and may miss all sequences.

**Fix:** Call `ansiRegex()` inside your loop or function so you always get a fresh instance with `lastIndex` at `0`:

```js
// ❌ Problematic — reusing a single instance
const regex = ansiRegex();
strings.forEach(s => console.log(regex.test(s)));

// ✅ Correct — fresh instance per call
strings.forEach(s => console.log(ansiRegex().test(s)));
```

---

### Issue 2 — `require('ansi-regex')` throws `Cannot find module`

**Symptom:** Your application throws `Error: Cannot find module 'ansi-regex'` at startup.

**Cause:** The package has not been installed in the current project, or you are running Node.js from a different working directory than where you ran `npm install`.

**Fix:** Run `npm install ansi-regex` from the root of your project (the directory containing `package.json`), then retry.

---

### Issue 3 — `.replace()` only removes the first ANSI sequence

**Symptom:** After calling `.replace(ansiRegex(), '')`, some ANSI sequences remain in the output string.

**Cause:** This should not happen with `ansiRegex()` because the returned regex always has the global (`g`) flag. If you are seeing partial replacement, you may be using a manually constructed regex without the `g` flag.

**Fix:** Always use `ansiRegex()` rather than a hand-rolled pattern, and verify the flag:

```js
console.log(ansiRegex().flags); // 'g'
```

---

### Issue 4 — Plain text strings unexpectedly match the regex

**Symptom:** `ansiRegex().test(str)` returns `true` for a string you believe contains no ANSI codes.

**Cause:** The string may contain the ESC character (`\u001B`) or another control character that is not visible when printed but is present in the raw data (for example, copy-pasted from a terminal).

**Fix:** Inspect the raw character codes to confirm:

```js
const codes = [...str].map(c => c.codePointAt(0).toString(16));
console.log(codes);
```

If `1b` (ESC) or `9b` (CSI) appears in the output, the string does contain ANSI sequences.
