Skip to content

Instantly share code, notes, and snippets.

@w3core
Last active December 9, 2015 11:03
Show Gist options
  • Save w3core/d6f31f37ccc79a3ae6da to your computer and use it in GitHub Desktop.
Save w3core/d6f31f37ccc79a3ae6da to your computer and use it in GitHub Desktop.
Extends String object with properties that returns colorized values of string. Can be useful for "console.log" output.
function StringStyler () {
function add (color, value) {
String.prototype.__defineGetter__(color, function(){
return "\u001b[" + value[0] + "m" + this + "\u001b[" + value[1] + "m";
});
}
var codes = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
blink: [5, 25],
inverse: [7, 27],
hidden: [8, 28],
strike: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
};
for (var i in codes) add(i, codes[i]);
}
@w3core
Copy link
Author

w3core commented Dec 9, 2015

Usage example

All available styles you can get from codes variable (see property name).

Code:

StringStyler();

// ...

console.log(
   "Blinked black string on red background".blink.black.bgRed
 + "\nItalic green string".italic.green
 + "\nUnderlined cyan string".underline.cyan
);

Result:

anim

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