Skip to content

Instantly share code, notes, and snippets.

@p8R
Created October 19, 2023 07:03
Show Gist options
  • Select an option

  • Save p8R/c94722f38816abd882229c754d487832 to your computer and use it in GitHub Desktop.

Select an option

Save p8R/c94722f38816abd882229c754d487832 to your computer and use it in GitHub Desktop.
JavaScript Code for handling colors in texts printed on console. Using ANSI color codes.
const ESC = '\x1B';
const RESET = ESC + '[0m';
const BOLD = ESC + '[1m';
const BOLDRESET = ESC + '[22m';
const CLRSCR = ESC + '[2J';
const CUR00 = ESC + '[H'
const CLS = CLRSCR + CUR00;
const fgCIdx = idx => ESC + `[38;5;${idx}m`;
const bgCIdx = idx => ESC + `[48;5;${idx}m`;
String.prototype.fgCIdx = function (clrIdx) {
return fgCIdx(clrIdx) + this + RESET;
}
String.prototype.bgCIdx = function (clrIdx) {
return bgCIdx(clrIdx) + this + RESET;
}
String.prototype.bold = function () {
return BOLD + this + BOLDRESET;
}
String.prototype.colors = function (fgIdx, bgIdx = null) {
let retString = "";
if (null != fgIdx) retString = ESC + fgCIdx(fgIdx);
if (null != bgIdx) retString += ESC + bgCIdx(bgIdx);
return retString + this + RESET;
}
@p8R
Copy link
Author

p8R commented Oct 19, 2023

Example color table:
zestawienie_kolorow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment