1

I am working on some javascript in a Node-RED function node right now and am running into an issue with a regex comparison.

var incoming = /^(?=.*?\bhello?\b)(?=.*?\bworld\b).*$/;
//var incoming = msg.payload[0].expression;
var sentence = "say hello to the world";
msg.payload = incoming.test(sentence);
return msg;

That works fine and msg.payload now has the value "true"

When I attempt to fetch the "incoming" variable from elsewhere instead of define it though, it fails.

//var incoming = /^(?=.*?\bhello?\b)(?=.*?\bworld\b).*$/;
var incoming = msg.payload[0].expression;
var sentence = "say hello to the world";
msg.payload = incoming.test(sentence);
return msg;

When setting the variable "incoming" this way it does not work and complains "TypeError: incoming.test is not a function". Fetching the typeof(incoming) returns "String" instead of "Object" like it was previously. msg.payload[0].expression contains the same string of characters as setting it inside of the function, it just has a different datatype. What is the best way to handle this?

Thanks!

Eric
  • 29
  • 5

1 Answers1

1
//var incoming = /^(?=.*?\bhello?\b)(?=.*?\bworld\b).*$/;
var incoming = RegExp(msg.payload[0].expression);
var sentence = "say hello to the world";
msg.payload = incoming.test(sentence);
return msg;

Works as expected, thank you to Garr!

Eric
  • 29
  • 5