In this article, we will learn to Add colors to Javascript console outputs. Adding colors to JavaScript console outputs allows you to distinguish different messages and make them more readable visually. to achieve this we have some common approaches.
- Using %c placeholder
- Using ANSI escape code
Approach 1: Using %C: The %c placeholder is a special syntax that enables the application of CSS styling to specified sections of the console output. It allows programmers to format console messages according to CSS principles,
Syntax:
console.log("%c neveropen", "color:green;");
Example: In this example, we are using the above-explained approach.
Javascript
let outputColor = "color:green; font-size:20px;" console.log( "%c neveropen" , outputColor); console.log( "%c A computer Science Portal" , outputColor); |
Output:
Approach 2: Using ANSI escape code: The output color of the console can be modified via JavaScript using ANSI escape codes. Console messages can have their appearance changed to improve readability and visual distinctiveness by inserting escape sequences, such as ‘\x1b[36m%s\x1b[0m’ for Green color.
Syntax:
console.log('\x1b[36m%s\x1b[0m', 'neveropen');
Example: In this example, we are using the above-explained approach to change our output color in the console.
Javascript
console.log( '\x1b[36m%s\x1b[0m' , 'neveropen' ); console.log( '\x1b[36m%s\x1b[0m' , 'A computer science portal' ) |
Output: