Chapter 3, Functions

Lets do the following exercises:

Exercises

  1. To convert Hex colors to RGB, perform the following:
            function getRGB(hex) { 
              return "rgb(" + 
                parseInt(hex[1] + hex[2], 16) + ", " + 
                parseInt(hex[3] + hex[4], 16) + ", " + 
                parseInt(hex[5] + hex[6], 16) + ")"; 
            } 
            Testing: 
            > getRGB("#00ff00"); 
                   "rgb(0, 255, 0)" 
            > getRGB("#badfad"); 
                   "rgb(186, 223, 173)" 
    

    One problem with this solution is that array access to strings like hex[0] is not in ECMAScript 3, although many browsers have supported it for a long time and is now described in ES5.

    However, But at this point in the book, there was as yet no discussion of objects and methods. Otherwise an ES3-compatible solution would be to use one of the string methods, such as charAt(), substring(), or ...

Get Object-Oriented JavaScript - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.