Format console.log with color and variables surrounding non-formatted text Format console.log with color and variables surrounding non-formatted text google-chrome google-chrome

Format console.log with color and variables surrounding non-formatted text


In order to get console.log() to be formatted such that it allows formatted and unformatted text in the same line, you must "reset" the css that you changed following the formatted css. For example, for the log to show up formatted like the code below

<span style="background: #ffa600; color: #ffe4b3;">Array[index0]</span> = <span style="background: yellow; color: black; font-style: italic;">http://www.google.com</span>

You would need your console.log() call looking like so:

Code

console.log("%c%s%c = %c%s","background:orange", "Array[index0]", "background:inherit;", "background:yellow;font-style: italic;", "google.com")

Result

result of code

Notice how after the first string is inserted into the string, I insert another %c formatter and give it the value of background:inherit which resets the elements backgrounds following that making them inherit the color from the console's defined css in the browser. That was the only thing you were missing from your code.


I recently wanted to solve for the same 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 = '';for (var split of splitText)  {    if (/^\{/.test(split)) {        cssRules.push('color:blue');    } else {        cssRules.push('color:inherit')    }    styledText += `%c${split} `};console.log(styledText , ...cssRules)

enter image description here


Example:

console.log('%c\uD83D\uDE09 Giant Rainbow Text!',             'font-weight:bold; font-size:50px;color:red; ' +            'text-shadow:3px 3px 0 red,6px 6px 0 orange,9px 9px 0 yellow, ' +            '12px 12px 0 green,15px 15px 0 blue,18px 18px 0 indigo,21px 21px 0 violet');

Produces:

Rainbow Text

Adapted from here.

Also see the documentation for console.log.