Problem Being Solved
What this library simplifies or enables
When working with terminal output, log files, or any text that has passed through a command-line environment, you frequently encounter ANSI escape sequences — special character sequences used to control colors, cursor movement, and text formatting. This page explains what problem ansi-regex solves and why detecting these sequences programmatically is harder than it looks.
The Problem: Hidden Characters in Terminal Output
ANSI escape sequences are invisible formatting instructions embedded directly in text strings. A string that looks like Hello, world! in a terminal might actually contain dozens of extra characters when you inspect its raw bytes. These sequences control things like:
- Text color and background color (e.g., red error messages, green success indicators)
- Text styling (bold, underline, italic)
- Cursor positioning and screen clearing
When you need to search through file contents, parse log output, strip formatting for storage, or measure the visible length of a string, these invisible sequences get in the way. A naive string search or length check will produce incorrect results because it counts the escape characters alongside the visible text.
Why Manual Pattern Matching Falls Short
ANSI escape sequences are not a single simple pattern. They come in two major families — sequences starting with \u001B (the classic ESC character) and those starting with \u009B (the C1 control code) — and each family branches into multiple sub-formats covering everything from simple color codes to complex device-control strings terminated by \u0007 (BEL).
Writing a regex that correctly captures all of these variants without false positives is non-trivial. Missing a sub-pattern means some escape sequences slip through undetected; writing a pattern that is too broad means legitimate content gets incorrectly matched.
What ansi-regex Solves
ansi-regex gives you a single, well-tested regular expression that reliably matches the full range of ANSI escape sequences. Rather than maintaining your own pattern, you call the library to generate the regex and use it against any string or file content you need to inspect.
Typical use cases include:
- Searching file contents or file names for text while ignoring terminal formatting
- Stripping ANSI codes from log files before writing to a database or display surface that does not understand them
- Testing whether a string contains any ANSI sequences at all
- Splitting or replacing escape sequences within a larger string-processing pipeline
Because the returned RegExp is created with the global (g) flag, you can use it directly with String.prototype.match(), String.prototype.replace(), or any other standard JavaScript regex method to iterate over every escape sequence found in a given input.
Check whether a string contains ANSI escape sequences
const ansiRegex = require('ansi-regex');
const raw = '\u001B[4mUnderlined text\u001B[0m';
const hasAnsi = ansiRegex().test(raw);
console.log(hasAnsi);
Expected output:
true
Find all escape sequences in a string
const ansiRegex = require('ansi-regex');
const raw = '\u001B[31mError:\u001B[0m file not found';
const matches = raw.match(ansiRegex());
console.log(matches);
Expected output:
[ '\u001B[31m', '\u001B[0m' ]
Strip ANSI sequences from file content before searching
const ansiRegex = require('ansi-regex');
const fs = require('fs');
const raw = fs.readFileSync('./output.log', 'utf8');
const clean = raw.replace(ansiRegex(), '');
// Now search or process `clean` without interference from escape codes
const hasFatalError = clean.includes('FATAL');
console.log('Contains fatal error:', hasFatalError);
Expected output (varies by file content):
Contains fatal error: true
- Getting Started / Installation — How to add
ansi-regexto your project and import it correctly. - API Reference:
ansiRegex()— Full details on the function signature and theRegExpit returns. - Usage Guide: Matching and Testing — Practical patterns for using the generated regex with
match(),test(), andreplace(). - ANSI Escape Code Specification — External reference for understanding the full range of sequences the library targets.