Friday, October 17, 2025
HomeLanguagesJavascriptHow to convert 3-digit color code to 6-digit color code using JavaScript...

How to convert 3-digit color code to 6-digit color code using JavaScript ?

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 the individual digits and paste them at the consecutive positions. 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)
</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)
</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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS