JavaScript regular expressions - match a series of hexadecimal numbers

Solution 1:

Use the g flag to match globally:

/[0-9A-Fa-f]{6}/g

Another good enhancement would be adding word boundaries:

/\b[0-9A-Fa-f]{6}\b/g

If you like you could also set the i flag for case insensitive matching:

/\b[0-9A-F]{6}\b/gi

Solution 2:

It depends on the situation, but I usually want to make sure my code can't silently accept (and ignore, or misinterpret) incorrect input. So I would normally do something like this.

var arr = s.split();
for (var i = 0; i < arr.length; i++) {
    if (!arr[i].match(/^[0-9A-Fa-f]{6}$/)
        throw new Error("unexpected junk in string: " + arr[i]);
    arr[i] = parseInt(arr[i], 16);
}

Solution 3:

try:

colorValues.match(/[0-9A-Fa-f]{6}/g); 

Note the g flag to Globally match.

Solution 4:

Alternatively to the answers above, a more direct approach might be:

/\p{Hex_Digit}{6}/ug

You can read more about Unicode Properties here.