【问题标题】:Remove a Particular Query string from URL [duplicate]从 URL 中删除特定查询字符串 [重复]
【发布时间】:2014-10-08 13:01:37
【问题描述】:

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

例如: 如果我有像

这样的网址

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

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

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, '');
}

//在谷歌上找到这个:

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 参数是查询字符串中的第二个参数,这将不起作用。 ('&' 仍将保留)

【问题讨论】:

    标签: javascript jquery html query-string


    【解决方案1】:

    再多搜索一点,然后你就可以找到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

    【讨论】:

    • 非常感谢.. 想知道我是如何错过链接的。我做了搜索! :(
    • 您能否提供一个解决方案,可以向点击事件添加参数并删除该点击事件的参数,即我想添加新参数或更改现有参数的值并删除现有参数之一一次点击
    • 能否针对区分大小写的问题进行更新?
    【解决方案2】:

    你可以这样做

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

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

    【讨论】:

    • 我试过你的方法..当我通过行业时效果很好..但是当我通过类别时..它坏了..你能告诉我有什么问题吗?我试过的网址:`'foo.com/en-gb/…'
    • @NightMonger 我的情况与您的情况相同,因为我的查询字符串参数已被编码。 @AmitJoki 的方法仍然适用于一些正则表达式更新:return url.replace(new RegExp(key + "[\\s\\S\\d]+?((?=$)|(?=&))"), "").replace("?&", "?").replace("&&", "&").replace(new RegExp("\\?$"), "");
    【解决方案3】:

    我建议:

    // 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>

    参考资料:

    【讨论】:

      猜你喜欢
      • 2016-10-25
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多