---
title: Usage Patterns
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/usage-patterns
---

# Usage Patterns

_Common integration patterns and best practices_

## Overview

This page walks you through the most common ways to integrate `ansi-regex` into your application. You will learn how to install the library, generate the ANSI escape code regular expression, and apply it to match or strip ANSI sequences from strings or file content. Understanding these patterns will help you reliably detect and handle terminal color codes and other ANSI control sequences in any Node.js project.

## Prerequisites

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

- **Node.js** installed (check with `node --version`)
- **npm** or **yarn** available in your environment
- A basic understanding of JavaScript regular expressions
- A project directory initialized with `npm init` or equivalent

## Installation

1. Open your terminal and navigate to your project root.

2. Install `ansi-regex` as a dependency:

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

3. If you prefer Yarn:

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

4. Confirm the package appears in your `package.json` under `dependencies`:

```json
{
  "dependencies": {
    "ansi-regex": "*"
  }
}
```

## Configuration

The `ansi-regex` API surface is intentionally minimal — calling the exported function generates a ready-to-use `RegExp` object. There are no constructor options or configuration flags exposed in the current API.

| Aspect | Detail |
|---|---|
| **Return type** | `RegExp` with the global (`g`) flag set |
| **Global flag** | Always enabled, so the regex finds **all** ANSI sequences in a string, not just the first |
| **Invocation** | Call `ansiRegex()` each time you need a fresh regex instance. Because the global flag maintains internal `lastIndex` state, **reusing a single instance across multiple `exec` or `test` calls on different strings can produce unexpected results**. Calling `ansiRegex()` gives you a clean instance with `lastIndex` reset to `0`. |

The underlying pattern matches:
- `ESC [` sequences (CSI — Control Sequence Introducer)
- `BEL`-terminated OSC (Operating System Command) sequences
- Both 7-bit (`\u001B`) and 8-bit (`\u009B`) escape openers

## Usage

**Importing the library**

Require `ansi-regex` and invoke it to obtain the regular expression:

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

const regex = ansiRegex();
```

---

**Testing whether a string contains ANSI sequences**

Use a fresh regex instance with `test()` to check for the presence of any ANSI codes:

```js
const hasAnsi = ansiRegex().test(inputString);
```

Create a new instance per call to avoid stale `lastIndex` state from the global flag.

---

**Extracting all ANSI sequences from a string**

Use `String.prototype.match()` with the regex to collect every sequence found:

```js
const sequences = inputString.match(ansiRegex());
// sequences is an Array of matched escape codes, or null if none found
```

---

**Stripping ANSI sequences from a string**

Replace all matches with an empty string to obtain plain text:

```js
const clean = inputString.replace(ansiRegex(), '');
```

---

**Processing file content**

Read a file and strip ANSI codes before further processing:

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

const raw = fs.readFileSync('./output.log', 'utf8');
const plain = raw.replace(ansiRegex(), '');
console.log(plain);
```

This pattern is useful when consuming log files generated by terminal-aware CLI tools.

## Examples

**Example 1 — Detecting ANSI codes**

Check if a string contains any ANSI escape sequences before deciding how to render it.

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

const colorString = '\u001B[4mUnderlined text\u001B[0m';
const plainString = 'No special formatting here';

console.log(ansiRegex().test(colorString));  // true
console.log(ansiRegex().test(plainString));  // false
```

**Expected output:**
```
true
false
```

---

**Example 2 — Extracting matched sequences**

Collect every ANSI sequence present in a string for inspection or logging.

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

const input = '\u001B[31mRed\u001B[0m and \u001B[32mGreen\u001B[0m';
const matches = input.match(ansiRegex());

console.log(matches);
```

**Expected output:**
```
[ '\u001B[31m', '\u001B[0m', '\u001B[32m', '\u001B[0m' ]
```

---

**Example 3 — Stripping ANSI codes**

Remove all escape sequences to produce a clean, human-readable string suitable for storage or plain-text rendering.

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

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

console.log(stripped);
```

**Expected output:**
```
Bold and Underlined
```

---

**Example 4 — Processing a log file**

Read a `.log` file produced by a colorized CLI tool and write a clean version to disk.

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

const raw = fs.readFileSync('./build.log', 'utf8');
const clean = raw.replace(ansiRegex(), '');

fs.writeFileSync('./build.clean.log', clean, 'utf8');
console.log('Cleaned log written to build.clean.log');
```

**Expected output:**
```
Cleaned log written to build.clean.log
```

## Troubleshooting

**Issue 1 — `test()` alternates between `true` and `false` on the same string**

*Symptom:* Calling `regex.test(str)` twice on the same string returns `true` the first time and `false` the second time (or vice versa).

*Cause:* You are reusing a single regex instance that has the global (`g`) flag. The `lastIndex` property advances after each successful match and does not reset automatically between calls.

*Fix:* Call `ansiRegex()` each time you need a fresh instance, or manually reset `lastIndex` between calls:
```js
// Preferred: create a new instance each time
const result = ansiRegex().test(myString);

// Alternative: reset lastIndex manually
const regex = ansiRegex();
regex.lastIndex = 0;
const result = regex.test(myString);
```

---

**Issue 2 — `match()` returns `null` even though the string looks like it has color codes**

*Symptom:* `str.match(ansiRegex())` returns `null` unexpectedly.

*Cause:* The string may use escape representations that were interpreted by your editor or shell before reaching JavaScript (e.g., the literal characters `\`, `u`, `0`, `0`, `1`, `B` rather than the actual Unicode escape `\u001B`).

*Fix:* Ensure the string is read or constructed with real byte values. When hardcoding test strings, use `\u001B` in a JavaScript string literal or read the raw bytes from a file or stream.

---

**Issue 3 — `require('ansi-regex')` throws `Cannot find module`**

*Symptom:* Your application crashes at startup with a module-not-found error.

*Cause:* The package was not installed, or was installed in a different working directory.

*Fix:* Run the installation command from your project root and verify `node_modules/ansi-regex` exists:
```bash
npm install ansi-regex
ls node_modules/ansi-regex
```

---

**Issue 4 — Stripping removes too much or too little content**

*Symptom:* After calling `.replace(ansiRegex(), '')`, some escape sequences remain or non-ANSI characters are removed.

*Cause:* The input may contain malformed or non-standard escape sequences, or the string encoding may not be UTF-8.

*Fix:* Confirm the source string is UTF-8 encoded. If you are reading from a file, pass `'utf8'` explicitly:
```js
const raw = fs.readFileSync('./file.log', 'utf8');
```
If sequences still remain, log `raw.charCodeAt(index)` around suspect positions to inspect the actual byte values.
