getColorCode

getColorCode converts any AnyColor value — a named 4-bit color, an 8-bit palette code, or a 24-bit RGB object — into its ANSI SGR escape sequence. It is the low-level building block that s() uses internally, exposed so you can construct raw ANSI strings when you need direct control.

Signature

function getColorCode(color: AnyColor | undefined, isBackground: boolean): string

Parameters

  • color: An AnyColor value — one of:Returns an empty string when undefined.
  • isBackground: When true, returns the background variant of the code; when false, returns the foreground variant.

Return Value

A raw ANSI escape string, for example:

  • Named foreground: "\x1b[32m" (green)
  • Named background: "\x1b[42m" (green bg)
  • 8-bit foreground: "\x1b[38;5;208m" (orange)
  • RGB foreground: "\x1b[38;2;255;136;0m"

Returns an empty string for undefined input.

Usage

import { getColorCode, cls } from "ts-better-console";

const fg = getColorCode("green", false); // "\x1b[32m"
const bg = getColorCode("black", true); // "\x1b[40m"
console.log(fg + bg + "Styled text" + cls);

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!