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

Eric Hepperle - CodeSlayer2010 picture Eric Hepperle - CodeSlayer2010 · Jan 27, 2017 · Viewed 7.5k times · Source

The issue

I wrote a function to demonstrate how to format Chrome developer console console.log() messages in a variety of ways. However, the one I'm having trouble with is printing a variable on the left with a color scheme, then a string in the middle with no styling, followed by another variable that is styled. Here is a graphic to illustrate:

![Screenshot showing desired output in console.

Also, this HTML/CSS code will demonstrate what I'm trying to produce in the developer console:

What I've tried that didn't work

This code from christianvuerings in Colors in JavaScript console works to print two different styles back-to-back:

console.log("%cHello, "+"World","color:red;","color:blue;")

I based my attempts on that code. The trouble is, Christian's code doesn't account for having non-formatted code sandwiched between formatted code, nor for having multiple variables. I made many tries to find the right combination of code and ordering, but the three most promising (to me) were these:

console.log("%c%s"+" is "+"%c%d"+"years old.", "color:red","Bob", "color:blue", 42).

console.log("%c%s"," is ","%c%d","years old.", "color:red","Bob", "color:blue", 42).

console.log("%c%s is %c%d years old.", "color:red", "Bob", "color:blue", 42).

My question

How can I print console.log() messages with multiple combinations of formatted and non-formatted code all on the same line?

Answer

Tomcat picture Tomcat · Jan 27, 2017

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.