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