Colorful Console Message
From Logic Wiki
Add some attitude to your console statement with the %c specifier
console.log('%cHello', 'color: green; background: yellow: font-size: 30px');
Contents
What is %c
%c: Applies CSS style rules to the output string as specified by the second parameter
Multiple Console Message Styles
To add multiple style, you just pre-pend the message with %c. The text before the directive will not be affected. Only the text after the directive will be styled using the CSS declarations in the parameter.
console.log( 'Nothing here %cHi Cat %cHey Bear', // Console Message 'color: blue', 'color: red' // CSS Style );
Passing the console CSS style as an Array
As you get more styles, the string can be quite long. Here’s a nifty trick you can do to clean things up. You can pass the styles as an array. And then you can use the join() method to turn the array style elements into a string.
// 1. Pass the css styles in an array
const styles = [
'color: green',
'background: yellow',
'font-size: 30px',
'border: 1px solid red',
'text-shadow: 2px 2px black',
'padding: 10px',
].join(';'); // 2. Concatenate the individual array item and concatenate them into a string separated by a semi-colon (;)
// 3. Pass the styles variable
console.log('%cHello There', styles);
Refactoring console message with %s
Beside cleaning up the console message by passing the styles as an array. We can also clean up the message using the %s specifier.
const styles = ['color: green', 'background: yellow'].join(';');
const message = 'Some Important Message Here';
// 3. Using the styles and message variable
console.log('%c%s', styles, message);