Skip to content
Related Articles
Open in App
Not now

Related Articles

How to add special characters to text to print in color in the console in JavaScript ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 15 Apr, 2021
Improve Article
Save Article
Like Article

The purpose of this article is to add special characters to text to print in color in the console in JavaScript.

Approach: The ANSI escape codes help change/specify the color of the output in the console. The color of the output of the console can be changed by adding these escape codes just before the actual text. 

Syntax: 

/*Codes for different Colors*/
black = "\x1b[30m"
red = "\x1b[31m"
green = "\x1b[32m"
yellow = "\x1b[33m"
blue = "\x1b[34m"
magenta = "\x1b[35m"
cyan = "\x1b[36m"
white = "\x1b[37m"

Example : 

Javascript




<script>
  console.log("\x1b[31m"+ "Red");
  console.log("\x1b[32m"+ "Green");
  console.log("\x1b[35m"+ "Magenta");
</script>

Output:

Note: The above task can be simplified by adding a custom helper function in the script which can be invoked with the color and data to be displayed in the console.

Example: The following is the JavaScript code for performing the task using a custom helper function.

Javascript




<script>
function colorHelper(color,data)
{  
  
   /* function receives 2 arguments color and data*/
   const black = "\x1b[30m";  
   const red = "\x1b[31m";
   const green = "\x1b[32m";
   const yellow = "\x1b[33m";
   const blue = "\x1b[34m";
   const magenta = "\x1b[35m";
   const cyan = "\x1b[36m";
   const white = "\x1b[37m";
   const arr=[];
  
   /* Storing the color codes in Array */
   arr[0] = black;  
   arr[1] = red;
   arr[2] = green;
   arr[3] = yellow;
   arr[4] = blue;
   arr[5] = magenta;
   arr[6] = cyan;
   arr[7] = white;
   console.log(arr[color]+data);
}
  
/* colorHelper function called with color and data */
colorHelper(1,"I am Red");  
colorHelper(2,"I am Green");
colorHelper(5,"I am Magenta");
</script>

Output: 


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!