I have this Odata query string (I’ve split the string over 3 lines for easier reading but in reality is a single line)
/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20
PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z%20and%20
ForeignBarcode%20eq%20'abcd1234'
In Javascript, I need to manipulate the purchase-date parameter like so, from
PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z
to
date(PurchaseDate)%20eq%202023-11-20
(that is: add the date function with brackets, change nIN to eq and strip the time)
Question: Is there a regex one liner to do this?
Here is my attempt
//define the input
let input =
"/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20PurchaseDate%20nIN%202023-02-02T23%3A00%3A00.000Z%20and%20ForeignBarcode%20eq%20'abcd1234"
//extract the date (using look behind and look ahead)
let rdate = /(?<=PurchaseDate%20nIN%20)d{4}-d{2}-d{2}(?=Td{2}%3Ad{2}%3Ad{2}.d{3}Z)/
let date = rdate.exec(input)
//use regex and some string manipulation to replace the orignal substring
input.replace(/PurchaseDate%20nIN%20d{4}-d{2}-d{2}Td{2}%3Ad{2}%3Ad{2}.d{3}Z/,`date(PurchaseDate%20eq%20${date[0]})`)
//result
// /odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20date(PurchaseDate)%20eq%202023-02-02)%20and%20ForeignBarcode%20eq%20'abcd1234
2
Answers
We can try the following regex replacement with the help of capture groups:
I would avoid regex for encoded strings. Consider parsing the URL first, then replacing what you need to. You can use the URL class to parse it first.