How to pass a Regex into a function node

I am trying to finish a Function node (part of a Sub-Flow) that will also allow the elements (usually a MQTT topic) of an array to be trimmed for purpose of feeding to a ui_chart. As these topics have many forms different uses of the so the easiest way was to extract using a Regex with the Regex changing on different implementations.
But I planned to pass the Regex to the subflow and thus the Function node as a string (ie msg,match) but the use of forward and back slashes starts to complicate matters as they are also used a escape characters in strings!
I have been using codepen as a sandpit for the Java and this where I have got to but now not even sure how it will work when I pass the Regex to the Function Node .
So is there a easir way a Regex (defined in a change Node) can be passed into a Function Node so it can be used in a string.replace() method.

var msg = {};
var output = {};
// var re= //;
msg.payload = "House/Rumpus/Temp";
msg.match = "/\w+\/(\w+)\/\w+/i";
if ('match' in msg) {
  msg.match = msg.match.replaceAll("\\" ,'\\\\');
  var modifier = msg.match.replace(/.+\/(.*)$/i, '$1');
  var pattern =  msg.match.replace(/\/(.+)\/.*$/, '$1');
  var re = new RegExp(pattern, modifier);
  //var re = /\w+\/(\w+)\/\w+/; 
  output.msg = msg.payload.replace(re , '$1')
};


re comes out as /w+/(w+)/w+/i whilst the commented out re = statement works but I need to define it dynamically outside the function node

note the above is simplified, the RegEx re will be applied to each element of an array (along with a lot of object reformatting)

Try

msg = {};
msg.payload = "House/Rumpus/Temp";
msg.match = "\\w+/\(\\w+)/\\w+";
msg.modifier = "i";
const match = msg.match;
const modifier = msg.modifier;
const pattern = new RegExp(match, modifier);
msg.output = msg.payload.replace(pattern , '$1');

return msg;

but would split not work

msg.position = 1;
msg.output = msg.payload.split("/")[msg.position];

OK, I was over thinking this, in the end the REGEX expression doesn't need and extra esc characters, I is just a string as below. then a couple of .replace functions extracts the pattern and modifier, RegExp to create a JS compatible Regex expresion and the it can be used in JS.

Details will be posted in a FLow (Extract Select data from SQL DB and reformat to load a ui-chart with historical data) I will publish on Nodered.org shortly

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.