FsliceAnsi
Bun

function

sliceAnsi

function sliceAnsi(
input: string,
start?: number,
end?: number,
options?: string | boolean | SliceAnsiOptions,
ambiguousIsNarrow?: boolean
): string;

Slice a string by visible column width, preserving ANSI escape codes.

Like String.prototype.slice, but indices are terminal column widths (accounting for wide CJK characters, emoji grapheme clusters, and zero-width joiners), and ANSI escape sequences (SGR colors, OSC 8 hyperlinks, etc.) are preserved and correctly re-opened/closed at the slice boundaries.

@param input

The string to slice

@param start

Starting column (default 0). Negative counts from end.

@param end

Ending column, exclusive (default end of string). Negative counts from end.

@param options

Optional behavior flags (e.g. ellipsis for truncation)

@param ambiguousIsNarrow

ambiguousIsNarrow as a positional arg, usable when the 4th arg is an ellipsis string (or undefined). Lets you pass both options without an object: sliceAnsi(s, 0, n, "\u2026", false).

@returns

The sliced string with ANSI codes intact

import { sliceAnsi } from "bun";

// Plain slice (replaces the `slice-ansi` npm package)
sliceAnsi("hello", 1, 4);                              // "ell"
sliceAnsi("\u001b[31mhello\u001b[39m", 1, 4);          // "\u001b[31mell\u001b[39m"
sliceAnsi("\u5b89\u5b81\u54c8", 0, 4);                 // "\u5b89\u5b81" (CJK: width 2 each)

// Truncation (replaces the `cli-truncate` npm package)
sliceAnsi("unicorn", 0, 4, "\u2026");           // "uni\u2026"
sliceAnsi("unicorn", -4, undefined, "\u2026");  // "\u2026orn"

Referenced types

interface SliceAnsiOptions

  • ambiguousIsNarrow?: boolean

    Count characters with East Asian Width "Ambiguous" as 1 column (narrow) instead of 2 (wide). Affects Greek, Cyrillic, some symbols, etc. that render wide in CJK-encoded terminals but narrow in Western ones.

    Matches the option of the same name in stringWidth and wrapAnsi.

  • ellipsis?: string

    If set, and content was cut at either edge of the requested range, insert this string at the cut edge(s). The ellipsis is counted against the visible-width budget and is emitted inside any active SGR styles (color, bold, etc.) so it inherits them, but outside any active OSC 8 hyperlink.

    This turns sliceAnsi into a drop-in cli-truncate replacement:

    • truncate-end: sliceAnsi(str, 0, max, { ellipsis: "\u2026" })
    • truncate-start: sliceAnsi(str, -max, undefined, { ellipsis: "\u2026" })