javascript 从 URL 中删除特定查询字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26257568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:44:02  来源:igfitidea点击:

Remove a Particular Query string from URL

javascriptjqueryhtmlquery-string

提问by Night Monger

I am trying to create a function to remove a particular querystring and its value from the url .

我正在尝试创建一个函数来从 url 中删除特定的查询字符串及其值。

For eg: if i have a url like

例如:如果我有一个像

var url = www.foo.com/test?name=kevin&gender=Male&id=1234

var url = www.foo.com/test?name=kevin&gender=Male&id=1234

If i pass name -> it should remove the key and value for name. the url should become

如果我通过 name -> 它应该删除 name 的键和值。网址应该变成

www.foo.com/test?gender=Male&id=1234

www.foo.com/test?gender=Male&id=1234

i have a Function ReturnRefinedURL(key,url)

我有一个功能 ReturnRefinedURL(key,url)

and i am doing this in the Function

我在函数中这样做

function ReturnRefinedURL(key,url)
{
var Value  = getParameterByName(key); // This returns kevin
var stringToBeRemoved = 'key +'='+ Value+'&'; // string becomes 'name=kevin&'
return url.replace(stringToBeRemoved, '');
}

//Found this in Google:

//在谷歌找到这个:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\[").replace(/[\]]/, "\]");
    var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

So when i call the method ReturnRefinedURL('name',window.location.href);

所以当我调用方法时 ReturnRefinedURL('name',window.location.href);

This works!!! But looking for a more elegant and fool proof method.
* This wont work if name parameter is the second one in the query string. (the '&' will still be retained)

这有效!!!但是正在寻找一种更优雅和防呆的方法。
* 如果 name 参数是查询字符串中的第二个,这将不起作用。(“&”仍将保留)

回答by SSA

Little bit of more search and then you can end up here:

多一点搜索,然后你可以在这里结束:

 var url = "www.foo.com/test?name=kevin&gender=Male&id=1234";
function removeURLParameter(url, parameter) {
    //prefer to use l.search if you have a location/link object
    var urlparts= url.split('?');   
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i= pars.length; i-- > 0;) {    
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        url= urlparts[0]+'?'+pars.join('&');
        return url;
    } else {
        return url;
    }
}

console.log(removeURLParameter(url, 'name'));
console.log(removeURLParameter(url, 'gender'));

Jsfiddle example

Jsfiddle 示例

回答by Amit Joki

You can simply do this

你可以简单地做到这一点

function returnRefinedURL(key, url){
   return url.replace(new RegExp(key + "=\w+"),"").replace("?&","?")
  .replace("&&","&"); 
}

Tested all the use-cases and the above works perfectly.

测试了所有用例,上述工作完美。

回答by David says reinstate Monica

I'd suggest:

我建议:

// obviously in real use, you could just access 'document.location'
// within the function:
function returnRefinedURL (key, url) {
    // separating the key-value ('search') portion of the URL from the rest:
    var urlParts = url.split('?');
    // if we have only a single array-element, or if the key to remove
    // is not found in the URL, we quit here and return the same unchanged URL:
    if (urlParts.length === 1 || url.indexOf(key) === -1 ) {
        // there were no parameters, or the
        // key wasn't present
        return url;
    }
    else {
        // otherwise, we split the key-value string on the '&' characters,
        // for an array of key=value strings:
        var keyValues = urlParts[1].split('&'),
        // filtering that array:
            refinedKeyValues = keyValues.filter(function (keyValuePair) {
                // keeping only those array elements that don't /start with/
                // the key to be removed:
                return keyValuePair.indexOf(key) !== 0;
            // joining the key=value pairs back into a string:
            }).join('&');
    }
    // returning the refined URL:
    return urlParts[0] + '?' + refinedKeyValues;
}

// beyond this point is entirely irrelevant, it's just for visual feedback:
document.getElementById('output').textContent = returnRefinedURL('name', 'www.foo.com/test?name=kevin&gender=Male&id=1234');
#output::before {
  content: 'output: ';
}
<div id="output"></div>

References:

参考: