• 0

hex to rgba conversion using javascript

Algorithm

  • get two characters from the input string at a time and convert it to the integer
    For example
let hex = 'ff00ff';
let r = parseInt(hex.substring(0, 2), 16) // 255
  • concat all the decimal numbers and return them

Even though the algorithm is simple there are few edge cases to cover before we can apply this algorithm

  • what if there is an additional white space in the string at the edges
  • what if the hex code starts with # sign
  • what if the short hand notation is used for the hex code
  • what if there is an additional white space in between characters
  • what if there are invalid characters in the string

Below solution implements the above algorithm with all those cases considered.

Solution