Skip to content

Instantly share code, notes, and snippets.

@Yuffster
Last active January 25, 2017 02:03
Show Gist options
  • Save Yuffster/631833194cc0c4d1c92a5c772e2e6e57 to your computer and use it in GitHub Desktop.
Save Yuffster/631833194cc0c4d1c92a5c772e2e6e57 to your computer and use it in GitHub Desktop.
{
let log = (str, styles) => {
styles = styles || {};
var args = [];
var active = [];
var flushed = true;
str = str.replace(/(?:(?:\[([^\]]+)\]|([^[]+)))/g, (a, b) => {
if (a.match(/^\[\//)) {
let changed = false;
b = b.replace(/^\//, '');
// Remove the tag from our active styles, in reverse order,
// and only the first matched tag.
active = active.filter((a) => {
if (a == (styles[b] || b) && !changed) {
changed = true;
return false;
} return true;
}).reverse();
flushed = false;
} else if (a.match(/^\[/)) {
// Add the tag to our active styles.
active.push(styles[b] || b);
flushed = false;
} else {
// It's a string.
if (!flushed) {
if (active.length>0) args.push(active.join(''));
else args.push('font-size:100%;');
flushed = true;
return "%c"+a;
} else {
return a;
}
}
return "";
});
args.unshift(str);
console.log(...args);
return args;
}
let styles = {
'red': 'color: red;',
'blue': 'color: blue;',
'green': 'color: green;',
'big': 'font-size: 500%;'
};
log("[red]Red[/red], [green]green[/green], [blue]blue[/blue].", styles);
log("[big]Big text.[/big]", styles);
let x = [
"%cBig red %cor green%c text.%c Normal.",
'BIG;RED',
'BIG;RED;GREEN',
'BIG;RED',
'RESET'
];
var r = log2("[big][red]Big red [green]or green[/green] text.[/big][/red] Normal.");
console.log(r);
r = log2("[big][red]Big red [green]or green[/green] text.[/big][/red] Normal.", styles);
console.log(r);
log2("[big][red]Big red [green][green]or green[/green] [/red]still green[/green] text.[/big] Normal.", styles);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment