Split a string into an array of paired numbers
I am trying to work out how to split the following hexadecimal string into an array of paired numbers.
At the moment i have the following:
function getRGB(hexVal) {
var substrHexVal = hex开发者_如何转开发Val.substring(1,hexVal.length);
var splitHexVal = substrHexVal.split("");
return splitHexVal;
}
var a = getRGB("#00FF00");
a;
Which returns the following:
["0", "0", "F", "F", "0", "0"]
But i need to get out this:
["00", "FF", "00"]
It is probably obvious what i am trying to do but i would like to do the rest myself.
Embrace the power of the functional side, Luke
a="#c0ffee"
"#c0ffee"
[1,3,5].map(function(o) {return a.slice(o,o+2)})
["c0", "ff", "ee"]
function getRGB(hexVal) {
return hexVal.toUpperCase().match(/[0-9A-F]{2}/g);
}
Take the string, convert it to uppercase, and extract all hexidecimal pairs with a simple regular expression. The uppercase conversion isn't strictly necessary, but it ensures that your hex pairs are consistent. You could just as easily make the alpha characters all lowercase (note that the "A-F" portion of a regex is now "a-f"):
function getRGB(hexVal) {
return hexVal.toLowerCase().match(/[0-9a-f]{2}/g);
}
Or if you just don't care, then you can make your regex case insensitive, using the "i" modifier:
function getRGB(hexVal) {
return hexVal.match(/[0-9a-f]{2}/gi);
}
Also, please note that none of these functions ensures that you get 3 pairs back. If you pass "_?!@#$#00FF00FF" to it, you're going to get ["00", "FF", "00", "FF"]. Similarly, if you pass "00FF0", you'll get ["00", "FF"] because only 2 complete pairs are found.
In other words, you'll want to add some error-checking.
You may want to pass through the string, and separate the pairs with a comma. Finally split the string on the commas:
function getRGB(hexVal) {
var commaSeperated = '';
// Removes the first character from the input string
hexVal = hexVal.substring(1, hexVal.length);
// Now let's separate the pairs by a comma
for (var i = 0; i < hexVal.length; i++) {
// Iterate through each char of hexVal
// Copy each char of hexVal to commaSeperated
commaSeperated += hexVal.charAt(i);
// After each pair of characters add a comma, unless this
// is the last char
commaSeperated += (i % 2 == 1 && i != (hexVal.length - 1)) ? ',' : '';
}
// split the commaSeperated string by commas and return the array
return commaSeperated.split(',');
}
console.log(getRGB("#00FF00")); // ["00", "FF", "00"]
function parseHexColor(colorVal) {
var regex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;
colorVal = colorVal.replace(regex,"$1,$2,$3");
return colorVal.split(",");
}
Obviously you'd want to test for bogus values, etc., and you could shorten it by a line, but this is a simple way to get what you want.
精彩评论