Skip to content
Related Articles

Related Articles

How to convert 3-digit color code to 6-digit color code using JavaScript ?
  • Last Updated : 12 Mar, 2021

In this article, we are converting a three-digit color HEX code into a six-digit color HEX code using JavaScript. To solve this problem, first we copy of the individual digits and paster at consecutive position. For example – #34E will be converted into #3344EE and #E90 will be converted into #EE9900.

Steps to convert 3-digit color code to 6-digit color code:

Step 1: The color code is in string format. So, apply the split method on the string. After applying the split method we got an array of elements.

Javascript




<script>
  
var digit = "39E"
  
digit = digit.split("")
  
console.log(digit)
  
// ["#", "3", "9", "E"]
</script>

Output:

["#", "3", "9", "E"]

Step 2: Now apply the map method and iterate over the array and return every item with concatenating to itself and check if the item is “#” then do not return the concatenated result, just return the item.



Javascript




<script>
  
var digit = "#39E";
  
digit = digit.split("").map((item)=>{
    if(item == "#"){return item}
        return item + item;
})
  
console.log(digit)
  
// ["#", "33", "99", "EE"]
</script>

Output:

["#", "33", "99", "EE"]

Step 3: Now use the join method to convert all the array items into a single string.

Javascript




<script>
  
var digit = "#39E"
  
digit = digit.split("").map((item)=>{
    if(item == "#"){return item}
        return item + item;
}).join("")
  
console.log(digit)
<script>

Output:

"#3399EE"

Step 4: In the above step, we are converting “#39E” but we can see the first element of this code is “#”, but if the user does not provide the “#” then you have to check if the first element is “#” then concatenate it with the resulting code. And this is our complete code.

Javascript




<script>
  
var digit = "#39E"
  
digit = digit.split("").map((item)=>{
    if(item == "#"){return item}
        return item + item;
}).join("")
  
if(digit[0] != "#"){
    digit = "#" + digit;
}
  
console.log(digit)
</script>

Output:

#3399EE
My Personal Notes arrow_drop_up
Recommended Articles
Page :