regex - 如果在纯正则表达式替换中不存在参数,则在 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
解决方案
这是一种方法
这里的想法是首先检查测试字符串是否包含我们正在测试的模式。如果它比我们不改变任何东西如果不是比我们搜索&
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);
推荐阅读
- python - 用于在 whatsapp 上向某人发送音频的 Python 脚本
- c# - 文本文件包含记录之间的回车
- react-native - 进程以非零代码退出:1 在创建 React Native App 期间使用 expo init 时出现子进程错误
- javascript - 从对象中删除元素 - javascript
- typescript - tsconfig 和环境声明中的项目引用
- python - 如何替换 YAML 文件中的多个相同值
- database - API 平台 - 针对大型数据库处理分页
- c# - NEST 中的模拟 Elasticsearch 客户端存在异步搜索方法问题
- java - 使用 Java 常量时未解决的引用
- unity3d - Unity 2D 物理碰撞检测无法正常工作