如果不存在纯正则表达式替换,则在 URL 查询字符串中插入参数

Inserting a parameter in a URL query string if not already present with pure regular expression substitution

我想在我的 ur 字符串上添加一个带有 &show_pinned_search=1?show_pinned_search=1 的参数(如果它尚不存在)。我可以添加参数 show_pinned_search=1 如果它不存在使用 negative lookahed 方法像 (?!show_pinned_search=1) 但难以决定前面的字符是 &?。测试演示:https://regex101.com/r/aNccK6/1

示例输入:

https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5&show_pinned_search=1
http://www.example.com/property/hyat-doral/HA-4509801?show_pinned_search=1
https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5
http://www.example.com/property/hyat-doral/HA-4509801
http://www.example.com/property/hyat-doral/HA-4509801?show_pinned_search=1
https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5

预期输出:

https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5&show_pinned_search=1
http://www.example.com/property/hyat-doral/HA-4509801?show_pinned_search=1
https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5&show_pinned_search=1
http://www.example.com/property/hyat-doral/HA-4509801?show_pinned_search=1
http://www.example.com/property/hyat-doral/HA-4509801?show_pinned_search=1
https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5&show_pinned_search=1

这是一种方法

这里的思路是先检查测试字符串是否包含我们要测试的模式。如果是,则我们不做任何更改,否则,我们将搜索 &? 的最后一个索引。无论哪个索引较高,我们都会添加该特殊字符以及 show_pinned_search=1

let arr = [`https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5&show_pinned_search=1`,

`http://www.example.com/property/hyat-doral/HA-4509801?show_pinned_search=1`,

`https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5`,

`http://www.example.com/property/hyat-doral/HA-4509801`,

`http://www.example.com/property/hyat-doral/HA-4509801?show_pinned_search=1`,

`https://www.example.com/property/villa-alexia/BC-1414?tes=dfgdf&fcb=5`,
];

let op = arr.map(e=>{
  let temp = e.match(/(\?|&)show_pinned_search=1/); 
  let ampIndex = e.lastIndexOf('&');
  let quesIndex = e.lastIndexOf('?');
  if(temp) return e;
  else return ampIndex > quesIndex ? e+'&show_pinned_search=1' : e+`?show_pinned_search=1`
})

console.log(op);

此正则表达式检查您是否必须插入 show_pinned_search=1 条目:

^([^?]+)(?:\??)(?!(?:.*)&?show_pinned_search=1(?:&.*)?$)(.*)$

一步一步:

  • ([^?]+)(?:\??):将url的第一部分与问号?匹配(如果有的话)。只截取了可能出现的问号之前的部分(group id </code></strong>).</li> <li><strong><code>(?!(?:.*)&?show_pinned_search=1(?:&.*)?$):向前看以确保 url[=49= 的前导部分没有出现 show_pinned_search=1 ]
  • (.*):检索前导部分(当然没有 show_pinned_search=1 出现)并捕获它(组 ID </code></strong>).</li> </ul> <p>然后进行这个替换:</p> <pre><code>?show_pinned_search=1&

    这里的诀窍是在问号之后插入show_pinned_search=1 ,所以如果有问号或符号,你就不必费心了&之前。

    这里的一个小缺点是,如果 url 没有以参数前导部分结尾或以问号结尾,您可以在字符串中获得前导 & 符号。然而,it's not a big deal.

    Working Regexp101.com fiddle.