skip to Main Content

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


  1. We can try the following regex replacement with the help of capture groups:

    var input = "PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z";
    var output = input.replace(/PurchaseDate%(d+).*?%(d{6})-(d{2})-(d{2})T.*?.d{3}[A-Z]/, "date(PurchaseDate)%$1eq%$2-$3-$4");
    console.log(output);
    Login or Signup to reply.
  2. 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.

    let path = "/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z%20and%20ForeignBarcode%20eq%20'abcd1234'";
    let url = new URL(path, "http://example.com");
    let filter = url.searchParams.get("$filter");
    filter = filter.replace(/PurchaseDate nIN (d{4}-d{2}-d{2})T.*?Z/, "date(PurchaseDate) = $1");
    url.searchParams.set("$filter", filter);
    console.log(filter);
    console.log(url.pathname + url.search);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search