Ways to Format Console Output in JavaScript
Last Updated :
27 Jun, 2023
In web development we use the browser’s console window to display messages such as errors or warnings or even personalised methods. Mostly it is used by programmers for testing and debugging process.
We can modify the console output according to our convenience to create personalised messages. We will discuss some approaches to format a console output through the examples given below.
Method 1: Using %c format specifiers.
- Write the message in console.log() statement
- Add %c specifier at beginning
- Declare the styling change in CSS format
- Print the output on console
Example 1: This example, implements the above approach
Javascript
console.log( "%cWelcome to GeeksforGeeks" , "color:green;" )
|
Output:
Example 2: This example store the CSS styling in a variable and the applies it to the message
Javascript
let style = `
color:green;
font-size:16px;
background-color:black;
`
console.log( "%cWelcome to GeeksforGeeks" , style);
|
Output:
There are some inbuilt methods of console which allow us to create personalized warnings and error messages
Method 2: Creating error and warnings messages
Example : This method implements the above approach.
Javascript
console.warn( "This is a warning" );
console.error( "This is an error" );
|
Output:
Share your thoughts in the comments
Please Login to comment...