jQuery 在链接单击时从 url 中添加和删除变量


jQuery add and remove variable from url on a link click

>我正在开发一个 Web 应用程序,我需要在其中添加和删除 URL 中的变量。我已经完成了单击将变量添加到 URL,但我添加了重复的变量。

href="http://localhost<?php echo $_SERVER['REQUEST_URI'];?>?budget=1-lakh-3-lakh"

首先点击链接:

http://localhost/auto/search.php?budget=1-2L

第二次点击同一链接:

http://localhost/auto/search.php?budget=1-2L&budget=1-2L

如果变量已经存在,我想从 URL 中删除变量,否则在单击链接时添加变量。我已经尝试了很多方法,但我没有得到结果。使用jQuery,我尝试了replace(), indexOf()

以下是从 URL 中删除特定参数的代码:

var url = location.href.replace(/&?budget=([^&]$|[^&]*)/i, "");  

或函数:

function removeParameterFromUrl(url,parameterName)
{
    var reg = new RegExp('&?'+parameterName+'=([^&]$|[^&]*)','gi');     
    return url.replace(reg, ""); 
}
location.href = removeParameterFromUrl(location.href,'budget')