Can Chrome\'s built-in JavaScript console display colors?
I want errors in red, warnings in orange and console.log
\'s in green. Is that possible?
I recently wanted to solve for a similar issue and constructed a small function to color only keywords i cared about which were easily identifiable by surrounding curly braces {keyword}
.
This worked like a charm:
var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
var splitText = text.split(' ');
var cssRules = [];
var styledText = '';
_.each(splitText, (split) => {
if (/^\{/.test(split)) {
cssRules.push('color:blue');
} else {
cssRules.push('color:inherit')
}
styledText += `%c${split} `
});
console.log(styledText , ...cssRules)
technically you could swap out the if statement with a switch/case statement to allow multiple stylings for different reasons
I wrote a npm
module that gives one the possibility to pass:
[MyFunction]
warning
, success
, info
and other predefined message typeshttps://www.npmjs.com/package/console-log-plus
Output (with custom prefixes):
clp({
type: 'ok',
prefix: 'Okay',
message: 'you bet'
});
clp({
type: 'error',
prefix: 'Ouch',
message: 'you bet'
});
clp({
type: 'warning',
prefix: 'I told you',
message: 'you bet'
});
clp({
type: 'attention',
prefix: 'Watch it!',
message: 'you bet'
});
clp({
type: 'success',
prefix: 'Awesome!',
message: 'you bet'
});
clp({
type: 'info',
prefix: 'FYI',
message: 'you bet'
});
clp({
type: 'default',
prefix: 'No fun',
message: 'you bet'
});
Output (without custom prefixes):
Input:
clp({
type: 'ok',
message: 'you bet'
});
clp({
type: 'error',
message: 'you bet'
});
clp({
type: 'warning',
message: 'you bet'
});
clp({
type: 'attention',
message: 'you bet'
});
clp({
type: 'success',
message: 'you bet'
});
clp({
type: 'info',
message: 'you bet'
});
clp({
type: 'default',
message: 'you bet'
});
To make sure the user won't render an invalid color, I wrote a color validator as well. It will validate colors by name
, hex
, rgb
, rgba
, hsl
or hsla
values
There are a series of inbuilt functions for coloring the console log:
//For pink background and red text
console.error("Hello World");
//For yellow background and brown text
console.warn("Hello World");
//For just a INFO symbol at the beginning of the text
console.info("Hello World");
//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code
//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')