首页 > 解决方案 > 如果在纯正则表达式替换中不存在参数,则在 URL 查询字符串中插入参数

问题描述

如果它尚不存在,我想在我的字符串上添加&show_pinned_search=1或添加一个参数。如果参数尚不存在,?show_pinned_search=1我可以使用负前瞻方法添加参数,例如但难以决定前面的字符是or 。测试演示:https ://regex101.com/r/aNccK6/1show_pinned_search=1(?!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
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

标签: regexquery-string

解决方案


这是一种方法

这里的想法是首先检查测试字符串是否包含我们正在测试的模式。如果它比我们不改变任何东西如果不是比我们搜索&and的最后一个索引?。无论哪个索引更高,我们都会添加该特殊字符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);


推荐阅读