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

时间:2014-10-08 13:01:38

标签: javascript jquery html query-string

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

例如: 如果我有一个像

的网址
  

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

如果我通过名字 - >它应该删除名称的键和值。网址应该成为

  

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

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

我在功能

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

//在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, " "));
}

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

这个有效!!!但寻找更优雅和万无一失的方法。
*如果name参数是查询字符串中的第二个参数,则此方法不起作用。 ('&'仍将保留)

3 个答案:

答案 0 :(得分:10)

稍微多一点的搜索,然后你可以结束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

答案 1 :(得分:1)

你可以简单地这样做

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

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

答案 2 :(得分:0)

我建议:



// 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>
&#13;
&#13;
&#13;

参考文献: