Writing in the front

This question comes from niuke.com and has been successfully tested. The author just started to learn front-end, ready to record their own learning process in nuggets, welcome and I prepare for the introduction of front-end partners to exchange and study together, also welcome you to criticize ~~~

Topic describes

Convert RGB color strings to hexadecimal form, such as RGB (255, 255, 255) to # FFFFFF

  1. The number of Spaces after each in RGB is not fixed
  2. Hexadecimal expressions use six lowercase characters
  3. If the input does not conform to RGB format, return the original input

The sample

The input

'rgb(255, 255, 255)'
Copy the code

The output

#ffffff
Copy the code

Answer key

function rgb2hex(sRGB) {
   let rgbArray = sRGB.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
   if(! rgbArray){return sRGB
   }else{
       let res = "#"
       // Find the array structure that match matches, where I starts at 1, not 0
       for(let i = 1; i <= 3; i++){
           let num = parseInt(rgbArray[i])
           if(num >= 0 && num <= 255) {If the value is less than 16, zero is added
               res += num < 16? "0" + num.toString(16) : num.toString(16)}else{
               return sRGB
           }
       }
       return res
   }  
}
Copy the code

knowledge

  1. Matching regular expressions

    The stringobject. match(regEXP) method returns an array where the 0th element holds the matching text and the remaining elements hold the text that matches the subexpression of the regular expression.

    Example:

    let sRGB = 'RGB (12,46,255)'
    let sArray = sRGB.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
    console.log(sArray);
    // Print the result
    Array(4)
    0: "RGB (12,46,255)"
    1: "12"
    2: "46"
    3: "255"
    groups: undefined
    index: 0
    input: "RGB (12,46,255)"
    length: 4
    __proto__: Array(0)
    Copy the code
  2. Conversions between numbers and strings parseInt(String, radix) and NumberObject.toString(radix)

    • The radix defaults to 10 and is resolved in decimal
  3. The boundary issue