Usage of regex in JSONata

Hi there!
I guess I am mediocre at programming - mostly on ANSI C and a bit object oriented.
Node-red is still fairly new to me.

For a Rest API call with multiple requests I am trying to modify the url to make the second request. In order to do so I need to modify values in the url-string and replace them with calculated values.

From an example I copied and modified the nodes and it works fine - appart from the url modification.
The JSONata code is:

$replace(
   url,
   /(limit=)(.+)(&offset=)(.+)/,
   "$1" & "$2" & "$3" & $string( $number($4) + 50)
)

For the url-string:
"url": "https://mywebsite/?limit=50&offset=100"

I would expect a result like this:
https://mywebsite/?limit=50&offset=150

What I am getting is missing the correct offset value.
https://mywebsite/?limit=50&offset=

I checked $4 it does indeed contain the former offset value of 100. To me it seems I am getting the syntax somehow wrong to address the $4 properly. I tried a million different formats that I found online, to no avail.

Can someone point me in the right direction please?
Thanks a lot!!
Cheers

$4 is not in the string replacement so is not seen by the regex replacement.
You would need to use $match() and bind a variable. Then you can use $number() on index 3
e.g.

($m := $match(url, /(limit=)(.+)(&offset=)(.+)/);
$r := $m.groups;
$replace(
   url,
   $m.match,
     $r[0] & $r[1] & $r[2] & ($number($r[3]) + 50)
)
)

Thx!
this worked for me as well as an alternative solution where I used variable in the respective string and dynamicall replace them with the correct value before use. The correct value I calculate from a msg element that is passed through the whole flow.

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