我有一个Odata查询字符串(为了便于阅读,我将字符串分成了3行,但实际上只有一行)
/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'
在JavaScript中,我需要像这样操作购买日期参数,
PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z
到
date(PurchaseDate)%20eq%202023-11-20
(that is:添加带括号的日期函数,将nIN更改为eq并删除时间)
问:是否有一个regex one liner来完成此操作?
以下是我的尝试
//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}(?=T\d{2}%3A\d{2}%3A\d{2}.\d{3}Z)/
let date = rdate.exec(input)
//use regex and some string manipulation to replace the orignal substring
input.replace(/PurchaseDate%20nIN%20\d{4}-\d{2}-\d{2}T\d{2}%3A\d{2}%3A\d{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条答案
按热度按时间jecbmhm31#
我会避免使用正则表达式来编码字符串。请考虑先解析URL,然后替换需要替换的内容。您可以先使用URL类来解析它。
qgelzfjb2#
我们可以在捕获组的帮助下尝试以下正则表达式替换: