s (similar to style)

The s function applies ANSI styles to a string for terminal output. It supports text color, background color, and text styles like bold, italic, underline, and strikethrough. By default, it appends a reset code at the end of the string.

Signature

function s(str: string, style: StyleOptions): string

Parameters

  • str: The string to style.
  • style: A StyleOptions object with:
    • color: Text color — a named color string (e.g. "red"), an 8-bit value via eightBit(n), or a 24-bit value via rgb(r,g,b) / hex("#...").
    • backgroundColor: Background color (same types as color).
    • styles: Array of text styles — "bold", "italic", "underline", "strikethrough".
    • endless: If true, omits the reset code at the end, allowing style to bleed into subsequent text.

Return Value

Returns a string with ANSI escape codes applied.

Usage

import { s } from "ts-better-console";

// Red text
console.log(s("Error!", { color: "red" }));

// Bold cyan with background
console.log(s("Highlight", {
color: "cyan",
backgroundColor: "blue",
styles: ["bold"],
}));

// Endless mode (no reset at end)
console.log(s("keeps going", { color: "green", endless: true }));

Extended Colors

In addition to named 4-bit colors, the s function supports 8-bit and 24-bit colors via the eightBit, rgb, and hex helper functions.

import { s, eightBit, rgb, hex, EightBitColor } from "ts-better-console";

// 8-bit color by code number
console.log(s("Orange", { color: eightBit(208) }));

// Using the EightBitColor enum
console.log(s("Pink", { color: eightBit(EightBitColor.Pink) }));

// 24-bit RGB color
console.log(s("Teal", { color: rgb(0, 128, 128) }));

// 24-bit color from hex string
console.log(s("Coral", { color: hex("#FF7F50") }));

Want to support this project?

If you find ts-better-console useful and want to support its development, consider starring the GitHub repository or buying me a coffee! Your support helps me dedicate more time to improving the library and adding new features.

Want to contribute to this project?

Contributions are welcome! If you're interested in improving the library, fixing bugs, or adding new features, feel free to check out the GitHub repository and submit a pull request. Whether you're a seasoned developer or new to open source, your contributions can make a difference!