Domanda

I am trying to pass a message using Node-Red (nodered.org) to a function.

So the message would be something like: Can I have 00ff00 please?

I am only interested in the hex code value and I need to parse the message and extract the hex with regex. This is the code I have:

var str = msg.payload;
var colorCode = str.match([A-Fa-f0-9]{6}/g);
return colorCode;

Something is not right and I get an error saying Unexpected token {

It doesn't work even if I put [A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9]/g I get an A is not defined error, probably because it doesn't consider it a regex.

È stato utile?

Soluzione

You need to put /

Use any of

str.match(/[A-Fa-f0-9]{6}/) or

str.match(/[a-f0-9]{6}/i)

instead of str.match([A-Fa-f0-9]{6})

Now if your string may contain multiple HEX codes then use the following instead:

str.match(/[a-f0-9]{6}/gi) -> This will fetch an array of all such HEX codes and hence you can access each such instance using index to the array as follows:

str="Can I have 00fA00 and B0fA0c please?"
hex_codes=str.match(/[a-f0-9]{6}/gi);
//hex_codes[0]=="00fA00" and hex_codes[1]=="B0fA0c"

Here is the fiddle demo

Altri suggerimenti

HEX color always starts from # and can has 3 or 6 digits value. Try /^#[a-z0-9]{3}([a-z0-9]{3})?$/i:

'#fff000'.match(/^#[a-z0-9]{3}([a-z0-9]{3})?$/i);//["#fff000", "000"]
'#fff'.match(/^#[a-z0-9]{3}([a-z0-9]{3})?$/i);//["#fff", undefined]

Also you have a misprint in(you forgot regexp start slash), fixed regexp:

/[A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9]/g

Shorter version for 6-digits only value:

'#fff000'.match(/^#[a-z0-9]{6}$/i);//["#fff000"]

Or multiple-color string check:

'#fff000 #aaabbb #ccc999'.match(/#[a-z0-9]{6}/gi);

As pointed on the comments, you've missed an / in front of your Regex to satisfy Javascript's Regex syntax.

Also, I'd like to suggest you to put boundaries on your regex, just to avoid some weird scenarios (like catching "BABABABABA"). Also, as pointed on the comments below, #FFF is a valid value for the color, so your Regex could be further improved. The result is the following:

/\b([a-f0-9]{3}|[a-f0-9]{6})\b/i

Catches:

Can I have C0ffee please?
The color is #FFF

Doesn't catch:

Testing 00000ff0000 just to be safe!
Making sure BABABABABA doesn't get catched also :)
Checking #ffff

As a final note, you may want to consider using the pattern #RRGGBB to catch those HEX colors, simply because you may find valid english words with 6 characters with letters from A-F. So, if you want to do that, just add an \# in front of your regex:

/\#\b([a-f0-9]{3}|[a-f0-9]{6})\b/i

Check this Regex101, it contains some examples of some inputs.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top