Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ansi-strip

npm install @ferrow/ansi-strip

CI

Strip/parse ANSI escape sequences: strip, visibleLength, truncateVisible, tokenize with color preservation.

Quick Start

import { strip, visibleLength, truncateVisible, tokenize } from "ansi-strip";

const colored = "\x1b[32mHello\x1b[0m World";

strip(colored);                  // "Hello World"
visibleLength(colored);          // 11
truncateVisible(colored, 5);     // "Hello\x1b[0m" (color reset appended)

tokenize(colored);
// [
//   { text: "Hello", codes: ["\x1b[32m"] },
//   { text: " World", codes: [] }
// ]

API

strip(text: string): string

Remove all ANSI escape sequences (SGR/colors, CSI sequences, OSC commands).

visibleLength(text: string): number

Return length of text without ANSI codes. Codepoint-aware (counts multi-byte UTF-8 correctly) but not full grapheme-cluster aware.

hasAnsi(text: string): boolean

Detect if text contains ANSI escape sequences.

truncateVisible(text: string, maxLen: number): string

Truncate text to visible length, preserving ANSI codes and appending reset (if codes were present).

tokenize(text: string): Token[]

Tokenize text into segments: {text: string, codes: string[]}. Each segment carries the ANSI codes active at that point. Useful for re-rendering with different styles.

Token shape:

interface Token {
  text: string;      // Visible text (no ANSI)
  codes: string[];   // ANSI codes active here
}

Limitations

  • Not full grapheme-aware: visibleLength counts UTF-8 codepoints, not grapheme clusters (emoji combining marks will be counted separately).
  • CSI/OSC coverage: Covers standard SGR (30-39, 90-97, 100-107, 1, 4, etc.), CSI sequences, and OSC (OSC 0-2, OSC 8 links). Some exotic sequences may not match.
  • No support for other terminal escape families (like termcap).

Part of the ferrow-toolkit collection · Sponsored by Ferrow

About

Strip/parse ANSI escape sequences: strip, visibleLength, truncateVisible, tokenize with color preservation

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages