w3resource

JavaScript: Extend a 3-digit color code to a 6-digit color code

JavaScript fundamental (ES6 Syntax): Exercise-20 with Solution

Write a JavaScript program to extend a 3-digit color code to a 6-digit color code.

  • Use Array.prototype.map(), String.prototype.split() and Array.prototype.join() to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
  • Array.prototype.slice() is used to remove # from string start since it's added once.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const extend_Hex = shortHex =>
  '#' +
  shortHex
    .slice(shortHex.startsWith('#') ? 1 : 0)
    .split('')
    .map(x => x + x)
    .join('');

console.log(extend_Hex('#03f'));
console.log(extend_Hex('05a'));

Sample Output:

#0033ff
#0055aa

Pictorial Presentation:

JavaScript Fundamental: Extend a 3-digit color code to a 6-digit color code

Flowchart:

flowchart: Extend a 3-digit color code to a 6-digit color code

Live Demo:

See the Pen javascript-basic-exercise-1-20 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to remove specified elements from the right of a given array of elements.
Next: Write a JavaScript program to get every nth element in an given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.