Extend Hex Value

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to extend a 3-digit color code to a 6-digit color code using JavaScript. We will be using Array methods such as map(), split(), and join() along with slice() to remove the # from the string start if present. This lab will help you understand how to manipulate strings and arrays in JavaScript to achieve a desired output.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") subgraph Lab Skills javascript/variables -.-> lab-28292{{"`Extend Hex Value`"}} javascript/data_types -.-> lab-28292{{"`Extend Hex Value`"}} javascript/arith_ops -.-> lab-28292{{"`Extend Hex Value`"}} javascript/comp_ops -.-> lab-28292{{"`Extend Hex Value`"}} javascript/higher_funcs -.-> lab-28292{{"`Extend Hex Value`"}} end

How to Extend a 3-Digit Color Code to a 6-Digit Color Code

To practice coding, open the Terminal/SSH and type node. You can use the following function to extend a 3-digit color code to a 6-digit color code:

const extendHex = (shortHex) =>
  "#" +
  shortHex
    .slice(shortHex.startsWith("#") ? 1 : 0)
    .split("")
    .map((x) => x + x)
    .join("");

To convert a 3-digit RGB notated hexadecimal color-code to the 6-digit form, follow these steps:

  • Use Array.prototype.map(), String.prototype.split(), and Array.prototype.join() to join the mapped array.
  • Use Array.prototype.slice() to remove # from the string start since it's added once.

Here are some examples:

extendHex("#03f"); // '#0033ff'
extendHex("05a"); // '#0055aa'

Summary

Congratulations! You have completed the Extend Hex Value lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like