Convert the obtained color value to hexadecimal

Source: Internet
Author: User

/**
*
* @ Authors Benjamin (@ Benjamin)
* @ Date 2013-12-30 12:49:55
* @ Version 1.0
*/
I. Analysis:
* Common color formats:
* A) background-color: red
* B) background-color: # 00F
* C) background-color: # 0000F
* D) background-color: rgb (0, 0, 255)

II. Implementation:

/*** [Convert parserColor to hexadecimal format] * @ param {[String]} value [color value to be converted] * @ return {[String]} [return Conversion after the color value, # Sort FF format] */function parserColor (value) {varstr = "", arr = [], arri = "", I = 0, vlen = value. length, colorObj = {"black": "000000", "red": "0000FF", "blue": "FF0000", "white": "FFFFFF ", "yellow": "FFFF00", "orange": "FFA500"}; // rgb (255,) if (/rgb /. test (value) {arr = value. match (/\ d +/g); vlen = arr. length; for (; I < Vlen; I ++) {arri = parseInt (arr [I]); // convert to hexadecimal str + = arri <10? "0" + arri. toString (16): arri. toString (16) ;}} else if (/^ #/. test (value) {// # 00fif (vlen = 4) {str = value. replace (/[A-Za-z0-9]/g, "$ &");} else if (vlen = 7) {// # ff1_str = value. replace (/^ # ([A-Za-z0-9] *)/, "$1");} else {str = "FFFFFF" ;}} else {// red/orangevalue = value. toLowerCase (); str = colorObj [value]? ColorObj [value]: "FFFFFF"; // mismatch the default value is white} return "#" + str. toUpperCase ();}


Iii. instances:

console.log(parserColor("white"));//#FFFFFFFconsole.log(parserColor("#00f"));//#0000FFconsole.log(parserColor("rgb(0,0,255)"));//#0000FF


Reprinted, please respect originality, and indicate the source Benjamin-front-end attacker. The address on this page is http://blog.csdn.net/cuew1987/article/details/17679033,thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.