1

I need help for a little task. I have a configuration file where I have to get the specified HEX color code:

; List of colors to use for
; the cards in the game
; Colour Memory

#3be6c4     
#e6e03b
#6f3be6 ; This purple shade could be nicer...
#4fe63b
#e63b3b 
#ff5a00 
#ff00de
#3b8fe6  

On my jQuery code, I know how to read the data from the file, but what I need now is to take ONLY the HEX codes (cutting out blank lines and comments), and put each one into an array. It's a regex matter I guess, but I'm kind of stocked :D

Many thanks

2
  • '#abcedef'.match(/^(#[a-z0-9]{6})/)[0] --> "#abcede" Commented Sep 20, 2013 at 18:57
  • 1
    @Brian, /#[a-f0-9]{6}/i matches hex, a-z is most certainly incorrect. Commented Sep 20, 2013 at 18:58

3 Answers 3

2

use /#[0-9a-f]{6}/ig as the regular expression, no need for jquery as it can all be easily done without the library.

var data = "your file data here";
hexcodes = data.match(/#[0-9a-f]{6}/ig);

hexcodes will contain

[
    "#3be6c4",
    "#e6e03b",
    "#6f3be6",
    "#4fe63b",
    "#e63b3b",
    "#ff5a00",
    "#ff00de",
    "#3b8fe6"
]
Sign up to request clarification or add additional context in comments.

2 Comments

# belongs inside the / chars.
It seems to don't work with that regex. It does with this one: /\b[0-9A-F]{6}\b/gi
1

It can be done without a regex as well.
Get the string content of the file, split on newlines and map the values, adding an empty string for anything that doesn't start with #, and then filter out the empties :

var arr = 'string with hex codes'.split('\n');

var hex = $.map(arr, function(color) {
    return $.trim(color).indexOf('#') === 0 ? $.trim(color).slice(0,7) : '';
}).filter(function(n) { return $.trim(n).length; });

FIDDLE

Comments

0

Here you go: http://jsfiddle.net/ECuux/1/

Uses this regex: /\b[0-9A-F]{6}\b/gi

The basic code I used:

var configFile; // Your file as a string

configFile.match(/\b[0-9A-F]{6}\b/gi)

1 Comment

I've just edited your regex by adding the "#" character, like that /#\b[0-9A-F]{6}\b/gi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.