Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Created February 18, 2012 20:30
Show Gist options
  • Save nhunzaker/1860933 to your computer and use it in GitHub Desktop.
Save nhunzaker/1860933 to your computer and use it in GitHub Desktop.
Converting Marak's color npm package from one mode to another
// Color Converter
function convertMode (str, from, to) {
var lex = [
'bold', 'italic', 'underline', 'inverse',
'white', 'grey', 'black',
'blue', 'cyan', 'green', 'magenta', 'red', 'yellow'
];
var styles = {
console: {
//styles
'bold' : ['\033[1m', '\033[22m'],
'italic' : ['\033[3m', '\033[23m'],
'underline' : ['\033[4m', '\033[24m'],
'inverse' : ['\033[7m', '\033[27m'],
//grayscale
'white' : ['\033[37m', '\033[39m'],
'grey' : ['\033[90m', '\033[39m'],
'black' : ['\033[30m', '\033[39m'],
//colors
'blue' : ['\033[34m', '\033[39m'],
'cyan' : ['\033[36m', '\033[39m'],
'green' : ['\033[32m', '\033[39m'],
'magenta' : ['\033[35m', '\033[39m'],
'red' : ['\033[31m', '\033[39m'],
'yellow' : ['\033[33m', '\033[39m']
},
browser: {
//styles
'bold' : ['<b>', '</b>'],
'italic' : ['<i>', '</i>'],
'underline' : ['<u>', '</u>'],
'inverse' : ['<span style="background-color:black;color:white;">', '</span>'],
//grayscale
'white' : ['<span style="color:white;">', '</span>'],
'grey' : ['<span style="color:grey;">', '</span>'],
'black' : ['<span style="color:black;">', '</span>'],
//colors
'blue' : ['<span style="color:blue;">', '</span>'],
'cyan' : ['<span style="color:cyan;">', '</span>'],
'green' : ['<span style="color:green;">', '</span>'],
'magenta' : ['<span style="color:magenta;">', '</span>'],
'red' : ['<span style="color:red;">', '</span>'],
'yellow' : ['<span style="color:yellow;">', '</span>']
},
none : {}
};
// Convert!
lex.forEach(function(style) {
styles.none[style] = ['',''];
var startFilter = new RegExp(styles[from][style][0], "g"),
endFilter = new RegExp(styles[to][style][1], "g");
str = str.replace(startFilter, styles[to][style][0]);
str = str.replace(endFilter, styles[to][style][1]);
});
return str;
}
if (typeof module !== 'undefined') {
module.exports = convertMode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment