如何添加或更新查询字符串参数?

时间:2011-05-14 00:46:39

标签: javascript jquery query-string

使用javascript如何在网址中添加查询字符串参数(如果不存在)或是否存在,更新当前值?我正在使用jquery进行客户端开发。

30 个答案:

答案 0 :(得分:442)

我编写了以下函数来完成我想要实现的目标:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

答案 1 :(得分:179)

我已经扩展了解决方案,并将其与我发现的另一个解决方案相结合,根据用户输入替换/更新/删除查询字符串参数并考虑网址锚。

不提供值将删除参数,提供参数将添加/更新参数。如果没有提供URL,它将从window.location中获取

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null)
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) 
                url += '#' + hash[1];
            return url;
        }
        else
            return url;
    }
}

<强>更新

删除查询字符串中的第一个参数时出现错误,我重新编写了正则表达式并测试了包含修复程序。

第二次更新

根据@JarónBarends的建议 - 调整值检查以检查未定义和null以允许设置0值

第三次更新

有一个错误,在hashtag之前直接删除querystring变量会丢失已修复的#标签符号

第四次更新

感谢@rooby指出第一个RegExp对象中的正则表达式优化。 由于@YonatanKarni找到的使用(\?|&amp;)问题,将初始正则表达式设置为([?&amp;])

第五次更新

在if / else语句中删除声明哈希变量

答案 2 :(得分:60)

URLSearchParams实用程序与window.location.search结合使用可能非常有用。例如:

if ('URLSearchParams' in window) {
    var searchParams = new URLSearchParams(window.location.search);
    searchParams.set("foo", "bar");
    window.location.search = searchParams.toString();
}

现在foo已设置为bar,无论它是否已存在。

但是,对window.location.search的上述分配会导致页面加载,因此如果不合乎需要,请使用History API,如下所示:

if ('URLSearchParams' in window) {
    var searchParams = new URLSearchParams(window.location.search)
    searchParams.set("foo", "bar");
    var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
    history.pushState(null, '', newRelativePathQuery);
}

现在您不需要编写自己的正则表达式或逻辑来处理查询字符串的可能存在。

但是,browser support很差,因为它目前是实验性的,仅在最近版本的Chrome,Firefox,Safari,iOS Safari,Android浏览器,Android Chrome和Opera中使用。如果您决定使用polyfill,请与https://msdn.microsoft.com/de-de/library/windows/hardware/ff538820%28v=vs.85%29.aspx一起使用。

更新:自我的原始答案以来,浏览器支持已有所改进。

答案 3 :(得分:42)

根据@ amateur的答案(现在纳入@j_walker_dev评论中的修复),但考虑到网址中有关哈希标记的评论,我使用以下内容:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  } else {
    var hash =  '';
    if( uri.indexOf('#') !== -1 ){
        hash = uri.replace(/.*#/, '#');
        uri = uri.replace(/#.*/, '');
    }
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";    
    return uri + separator + key + "=" + value + hash;
  }
}

修改了正则表达式中的[?|&],当然应该是[?&],如评论中所指出

编辑:支持删除URL参数的替代版本。我使用value === undefined作为指示删除的方式。可以根据需要使用value === false甚至单独的输入参数。

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
  if( value === undefined ) {
    if (uri.match(re)) {
        return uri.replace(re, '$1$2');
    } else {
        return uri;
    }
  } else {
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
    var hash =  '';
    if( uri.indexOf('#') !== -1 ){
        hash = uri.replace(/.*#/, '#');
        uri = uri.replace(/#.*/, '');
    }
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";    
    return uri + separator + key + "=" + value + hash;
  }
  }  
}

https://jsfiddle.net/bp3tmuxh/1/

中查看此操作

答案 4 :(得分:20)

这是我的图书馆:https://github.com/Mikhus/jsurl

var u = new Url;
u.query.param='value'; // adds or replaces the param
alert(u)

答案 5 :(得分:10)

window.location.search是读/写。

然而 - 修改查询字符串将重定向您所在的页面并从服务器刷新。

如果您尝试做的是保持客户端状态(并且可能使其成为可书签状态),您将需要修改URL哈希而不是查询字符串,这会使您保持在同一页面上(窗口) .location.hash是读/写)。这就像twitter.com这样的网站就是这样做的。

您还需要后退按钮才能工作,您必须将javascript事件绑定到哈希更改事件,这是一个很好的插件http://benalman.com/projects/jquery-hashchange-plugin/

答案 6 :(得分:9)

如果未设置或想要使用新值更新,您可以使用:

window.location.search = 'param=value'; // or param=new_value

顺便说一下,这是简单的Javascript。

修改

您可能想尝试使用jquery query-object插件

  

window.location.search =   jQuery.query.set(“param”,5);

答案 7 :(得分:9)

我意识到这个问题已经过时了,并且已经得到了解决,但是我在这里捅了它。我试图在这里重新发明轮子,因为我正在使用当前接受的答案,并且最近对URL片段的错误处理让我误入了项目。

功能如下。它很长,但它尽可能具有弹性。我会喜欢缩短/改进它的建议。我为它(或其他类似的功能)放了一个小的jsFiddle test suite。如果一个函数可以通过那里的每一个测试,我说它可能会很好。

更新:我遇到了using the DOM to parse URLs的酷炫功能,所以我在这里加入了这项技术。它使功能更短,更可靠。道具给该函数的作者。

/**
 * Add or update a query string parameter. If no URI is given, we use the current
 * window.location.href value for the URI.
 * 
 * Based on the DOM URL parser described here:
 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
 *
 * @param   (string)    uri     Optional: The URI to add or update a parameter in
 * @param   (string)    key     The key to add or update
 * @param   (string)    value   The new value to set for key
 *
 * Tested on Chrome 34, Firefox 29, IE 7 and 11
 */
function update_query_string( uri, key, value ) {

    // Use window URL if no query string is provided
    if ( ! uri ) { uri = window.location.href; }

    // Create a dummy element to parse the URI with
    var a = document.createElement( 'a' ), 

        // match the key, optional square brackets, an equals sign or end of string, the optional value
        reg_ex = new RegExp( key + '((?:\\[[^\\]]*\\])?)(=|$)(.*)' ),

        // Setup some additional variables
        qs,
        qs_len,
        key_found = false;

    // Use the JS API to parse the URI 
    a.href = uri;

    // If the URI doesn't have a query string, add it and return
    if ( ! a.search ) {

        a.search = '?' + key + '=' + value;

        return a.href;
    }

    // Split the query string by ampersands
    qs = a.search.replace( /^\?/, '' ).split( /&(?:amp;)?/ );
    qs_len = qs.length; 

    // Loop through each query string part
    while ( qs_len > 0 ) {

        qs_len--;

        // Remove empty elements to prevent double ampersands
        if ( ! qs[qs_len] ) { qs.splice(qs_len, 1); continue; }

        // Check if the current part matches our key
        if ( reg_ex.test( qs[qs_len] ) ) {

            // Replace the current value
            qs[qs_len] = qs[qs_len].replace( reg_ex, key + '$1' ) + '=' + value;

            key_found = true;
        }
    }   

    // If we haven't replaced any occurrences above, add the new parameter and value
    if ( ! key_found ) { qs.push( key + '=' + value ); }

    // Set the new query string
    a.search = '?' + qs.join( '&' );

    return a.href;
}

答案 8 :(得分:9)

以下是我的方法:location.params()函数(如下所示)可用作getter或setter。例子:

鉴于网址为http://example.com/?foo=bar&baz#some-hash

  1. location.params()将返回包含所有查询参数的对象:{foo: 'bar', baz: true}
  2. location.params('foo')将返回'bar'
  3. location.params({foo: undefined, hello: 'world', test: true})会将网址更改为http://example.com/?baz&hello=world&test#some-hash
  4. 以下是params()函数,可以选择将其分配给window.location对象。

    location.params = function(params) {
      var obj = {}, i, parts, len, key, value;
    
      if (typeof params === 'string') {
        value = location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[&#$]?'));
        return value ? value[1] : undefined;
      }
    
      var _params = location.search.substr(1).split('&');
    
      for (i = 0, len = _params.length; i < len; i++) {
        parts = _params[i].split('=');
        if (! parts[0]) {continue;}
        obj[parts[0]] = parts[1] || true;
      }
    
      if (typeof params !== 'object') {return obj;}
    
      for (key in params) {
        value = params[key];
        if (typeof value === 'undefined') {
          delete obj[key];
        } else {
          obj[key] = value;
        }
      }
    
      parts = [];
      for (key in obj) {
        parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
      }
    
      location.search = parts.join('&');
    };
    

答案 9 :(得分:6)

这是我的偏好,它涵盖了我能想到的情况。任何人都可以想到一种方法将它减少到一个替换?

pantopress

答案 10 :(得分:5)

我知道这已经很老了,但我想在这里解雇工作版

&#13;
&#13;
function addOrUpdateUrlParam(uri, paramKey, paramVal) {
  var re = new RegExp("([?&])" + paramKey + "=[^&#]*", "i");
  if (re.test(uri)) {
    uri = uri.replace(re, '$1' + paramKey + "=" + paramVal);
  } else {
    var separator = /\?/.test(uri) ? "&" : "?";
    uri = uri + separator + paramKey + "=" + paramVal;
  }
  return uri;
}

jQuery(document).ready(function($) {
  $('#paramKey,#paramValue').on('change', function() {
    if ($('#paramKey').val() != "" && $('#paramValue').val() != "") {
      $('#uri').val(addOrUpdateUrlParam($('#uri').val(), $('#paramKey').val(), $('#paramValue').val()));
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="width:100%" type="text" id="uri" value="http://www.example.com/text.php">
<label style="display:block;">paramKey
  <input type="text" id="paramKey">
</label>
<label style="display:block;">paramValue
  <input type="text" id="paramValue">
</label>
&#13;
&#13;
&#13;

注意这是@elreimundo

的修改版本

答案 11 :(得分:3)

URLSearchParams如此简单,所有现代浏览器(caniuse)都支持。

let p = new URLSearchParams();
p.set("foo", "bar");
p.set("name", "Jack & Jill?");
console.log("http://example.com/?" + p.toString());

如果要修改现有的URL,请像这样构造对象:new URLSearchParams(window.location.search),并将字符串分配给window.location.search

答案 12 :(得分:2)

这是一个较短的版本,负责

  • 使用或不使用给定参数进行查询
  • 使用多个参数值进行查询
  • 包含哈希的查询

代码:

var setQueryParameter = function(uri, key, value) {
  var re = new RegExp("([?&])("+ key + "=)[^&#]*", "g");
  if (uri.match(re)) 
    return uri.replace(re, '$1$2' + value);

  // need to add parameter to URI
  var paramString = (uri.indexOf('?') < 0 ? "?" : "&") + key + "=" + value;
  var hashIndex = uri.indexOf('#');
  if (hashIndex < 0)
    return uri + paramString;
  else
    return uri.substring(0, hashIndex) + paramString + uri.substring(hashIndex);
}

可以找到正则表达式说明here

注意:此解决方案基于@amateur答案,但有许多改进。

答案 13 :(得分:2)

基于@ellemayo给出的答案,我提出了以下解决方案,允许在需要时禁用哈希标记:

function updateQueryString(key, value, options) {
    if (!options) options = {};

    var url = options.url || location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;

    hash = url.split('#');
    url = hash[0];
    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            url = url.replace(re, '$1' + key + "=" + value + '$2$3');
        } else {
            url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
        }
    } else if (typeof value !== 'undefined' && value !== null) {
        var separator = url.indexOf('?') !== -1 ? '&' : '?';
        url = url + separator + key + '=' + value;
    }

    if ((typeof options.hash === 'undefined' || options.hash) &&
        typeof hash[1] !== 'undefined' && hash[1] !== null)
        url += '#' + hash[1];
    return url;
}

这样称呼:

updateQueryString('foo', 'bar', {
    url: 'http://my.example.com#hash',
    hash: false
});

结果:

http://my.example.com?foo=bar

答案 14 :(得分:2)

我的看法from here(与“use strict”兼容;并不真正使用jQuery):

function decodeURIParams(query) {
  if (query == null)
    query = window.location.search;
  if (query[0] == '?')
    query = query.substring(1);

  var params = query.split('&');
  var result = {};
  for (var i = 0; i < params.length; i++) {
    var param = params[i];
    var pos = param.indexOf('=');
    if (pos >= 0) {
        var key = decodeURIComponent(param.substring(0, pos));
        var val = decodeURIComponent(param.substring(pos + 1));
        result[key] = val;
    } else {
        var key = decodeURIComponent(param);
        result[key] = true;
    }
  }
  return result;
}

function encodeURIParams(params, addQuestionMark) {
  var pairs = [];
  for (var key in params) if (params.hasOwnProperty(key)) {
    var value = params[key];
    if (value != null) /* matches null and undefined */ {
      pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
    }
  }
  if (pairs.length == 0)
    return '';
  return (addQuestionMark ? '?' : '') + pairs.join('&');
}

//// alternative to $.extend if not using jQuery:
// function mergeObjects(destination, source) {
//   for (var key in source) if (source.hasOwnProperty(key)) {
//     destination[key] = source[key];
//   }
//   return destination;
// }

function navigateWithURIParams(newParams) {
  window.location.search = encodeURIParams($.extend(decodeURIParams(), newParams), true);
}

使用示例:

// add/update parameters
navigateWithURIParams({ foo: 'bar', boz: 42 });

// remove parameter
navigateWithURIParams({ foo: null });

// submit the given form by adding/replacing URI parameters (with jQuery)
$('.filter-form').submit(function(e) {
  e.preventDefault();
  navigateWithURIParams(decodeURIParams($(this).serialize()));
});

答案 15 :(得分:1)

使用此功能可基于jquery从URL添加,删除和修改查询字符串参数

/**
@param String url
@param object param {key: value} query parameter
*/
function modifyURLQuery(url, param){
    var value = {};

    var query = String(url).split('?');

    if (query[1]) {
        var part = query[1].split('&');

        for (i = 0; i < part.length; i++) {
            var data = part[i].split('=');

            if (data[0] && data[1]) {
                value[data[0]] = data[1];
            }
        }
    }

    value = $.extend(value, param);

    // Remove empty value
    for (i in value){
        if(!value[i]){
            delete value[i];
        }
    }

    // Return url with modified parameter
    if(value){
        return query[0] + '?' + $.param(value);
    } else {
        return query[0];
    }
}

添加新内容并将现有参数修改为url

var new_url = modifyURLQuery("http://google.com?foo=34", {foo: 50, bar: 45});
// Result: http://google.com?foo=50&bar=45

删除现有的

var new_url = modifyURLQuery("http://google.com?foo=50&bar=45", {bar: null});
// Result: http://google.com?foo=50

答案 16 :(得分:1)

不使用正则表达式的 。支持&#39; hash&#39;网址末尾的锚点以及多个问号字符(?)。应该比正则表达式方法稍快。

function setUrlParameter(url, key, value) {
  var parts = url.split("#", 2), anchor = parts.length > 1 ? "#" + parts[1] : '';
  var query = (url = parts[0]).split("?", 2);
  if (query.length === 1) 
    return url + "?" + key + "=" + value + anchor;

  for (var params = query[query.length - 1].split("&"), i = 0; i < params.length; i++)
    if (params[i].toLowerCase().startsWith(key.toLowerCase() + "="))
      return params[i] = key + "=" + value, query[query.length - 1] = params.join("&"), query.join("?") + anchor;

  return url + "&" + key + "=" + value + anchor
}

答案 17 :(得分:1)

使用ES6和jQuery将参数列表附加到现有网址的代码:

class UrlBuilder {
    static appendParametersToUrl(baseUrl, listOfParams) {

        if (jQuery.isEmptyObject(listOfParams)) {
            return baseUrl;
        }

        const newParams = jQuery.param(listOfParams);

        let partsWithHash = baseUrl.split('#');
        let partsWithParams = partsWithHash[0].split('?');

        let previousParams = '?' + ((partsWithParams.length === 2) ? partsWithParams[1] + '&' : '');
        let previousHash = (partsWithHash.length === 2) ? '#' + partsWithHash[1] : '';

        return partsWithParams[0] + previousParams + newParams + previousHash;
    }
}

listOfParams类似于

const listOfParams = {
    'name_1': 'value_1',
    'name_2': 'value_2',
    'name_N': 'value_N',
};

用法示例:

    UrlBuilder.appendParametersToUrl(urlBase, listOfParams);

快速测试:

    url = 'http://hello.world';
    console.log('=> ', UrlParameters.appendParametersToUrl(url, null));
    // Output:  http://hello.world

    url = 'http://hello.world#h1';
    console.log('=> ', UrlParameters.appendParametersToUrl(url, null));
    // Output:  http://hello.world#h1

    url = 'http://hello.world';
    params = {'p1': 'v1', 'p2': 'v2'};
    console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
    // Output: http://hello.world?p1=v1&p2=v2

    url = 'http://hello.world?p0=v0';
    params = {'p1': 'v1', 'p2': 'v2'};
    console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
    // Output: http://hello.world?p0=v0&p1=v1&p2=v2

    url = 'http://hello.world#h1';
    params = {'p1': 'v1', 'p2': 'v2'};
    console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
   // Output: http://hello.world?p1=v1&p2=v2#h1

    url = 'http://hello.world?p0=v0#h1';
    params = {'p1': 'v1', 'p2': 'v2'};
    console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
    // Output: http://hello.world?p0=v0&p1=v1&p2=v2#h1

答案 18 :(得分:1)

您可以使用浏览器的原生 URL API 以相当简单的方式完成此操作。

const url = new URL(location.href);
url.searchParams.set('PARAM_HERE', VALUE_HERE);
history.pushState(null, '', url);

这将保留有关 URL 的所有内容,并且仅更改或添加一个查询参数。如果您不希望它创建新的浏览器历史记录条目,也可以使用 replaceState 代替 pushState

答案 19 :(得分:0)

这应该达到目的:

function updateQueryString(url, key, value) {
    var arr =  url.split("#");
    var url = arr[0];
    var fragmentId = arr[1];
    var updatedQS = "";
    if (url.indexOf("?") == -1) {
        updatedQS = encodeURIComponent(key) + "=" + encodeURIComponent(value);
    }
    else {
        updatedQS = addOrModifyQS(url.substring(url.indexOf("?") + 1), key, value); 
    }
    url = url.substring(0, url.indexOf("?")) + "?" + updatedQS;
    if (typeof fragmentId !== 'undefined') {
        url = url + "#" + fragmentId;
    }
    return url;
}

function addOrModifyQS(queryStrings, key, value) {
    var oldQueryStrings = queryStrings.split("&");
    var newQueryStrings = new Array();
    var isNewKey = true;
    for (var i in oldQueryStrings) {
        var currItem = oldQueryStrings[i];
        var searchKey = key + "=";
        if (currItem.indexOf(searchKey) != -1) {
            currItem = encodeURIComponent(key) + "=" + encodeURIComponent(value);
            isNewKey = false;
        }
        newQueryStrings.push(currItem);
    }
    if (isNewKey) {
        newQueryStrings.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
    }
    return newQueryStrings.join("&");
}   

答案 20 :(得分:0)

此页面上有许多尴尬且不必要的复杂答案。评价最高的一个,@业余爱好者,虽然它在RegExp中有一些不必要的毛病,但它还是相当不错的。这是一个稍微更优化的解决方案,使用更清晰的RegExp和更清晰的replace调用:

function updateQueryStringParamsNoHash(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=[^&]*", "i");
  return re.test(uri)
       ? uri.replace(re, '$1' + key + "=" + value)
       : uri + separator + key + "=" + value
  ;
}

作为额外的好处,如果uri不是字符串,那么您尝试在可能无法实现这些方法的内容上调用matchreplace时会遇到错误

如果你想处理一个哈希的情况(并且你已经检查过格式正确的HTML),你可以利用现有的函数,而不是编写一个包含相同逻辑的新函数:

function updateQueryStringParams(url, key, value) {
    var splitURL = url.split('#');
    var hash = splitURL[1];
    var uri = updateQueryStringParamsNoHash(splitURL[0]);
    return hash == null ? uri : uri + '#' + hash;
}

或者你可以对@ Adam的其他优秀答案稍作修改:

function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=[^&#]*", "i");
  if (re.test(uri)) {
    return uri.replace(re, '$1' + key + "=" + value);
  } else {
    var matchData = uri.match(/^([^#]*)(#.*)?$/);
    var separator = /\?/.test(uri) ? "&" : "?";    
    return matchData[0] + separator + key + "=" + value + (matchData[1] || '');
  }
}

答案 21 :(得分:0)

如果您想一次设置多个参数:

function updateQueryStringParameters(uri, params) {
    for(key in params){
      var value = params[key],
          re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
          separator = uri.indexOf('?') !== -1 ? "&" : "?";
      if (uri.match(re)) {
        uri = uri.replace(re, '$1' + key + "=" + value + '$2');
      }
      else {
        uri = uri + separator + key + "=" + value;
      }
    }
    return uri;
}

与@ amateur相同的功能

如果jslint给出错误,请在for循环后添加

if(params.hasOwnProperty(key))

答案 22 :(得分:0)

这是使用锚点HTML元素的内置属性的替代方法:

  • 处理多值参数。
  • 无需修改#片段或查询字符串本身以外的任何内容。
  • 可能更容易阅读?但它更长。

&#13;
&#13;
    var a = document.createElement('a'),

	getHrefWithUpdatedQueryString = function(param, value) {
	    return updatedQueryString(window.location.href, param, value);
	},

	updatedQueryString = function(url, param, value) {
	    /*
	     A function which modifies the query string 
             by setting one parameter to a single value.

	     Any other instances of parameter will be removed/replaced.
	     */
	    var fragment = encodeURIComponent(param) + 
                           '=' + encodeURIComponent(value);

	    a.href = url;

	    if (a.search.length === 0) {
		a.search = '?' + fragment;
	    } else {
		var didReplace = false,
		    // Remove leading '?'
		    parts = a.search.substring(1)
		// Break into pieces
			.split('&'),

		    reassemble = [],
		    len = parts.length;

		for (var i = 0; i < len; i++) {
		    
		    var pieces = parts[i].split('=');
		    if (pieces[0] === param) {
			if (!didReplace) {
			    reassemble.push('&' + fragment);
			    didReplace = true;
			}
		    } else {
			reassemble.push(parts[i]);
		    }
		}

		if (!didReplace) {
		    reassemble.push('&' + fragment);
		}

		a.search = reassemble.join('&');
	    }

	    return a.href;
	};
&#13;
&#13;
&#13;

答案 23 :(得分:0)

通过使用jQuery,我们可以像下面这样

var query_object = $.query_string;
query_object["KEY"] = "VALUE";
var new_url = window.location.pathname + '?'+$.param(query_object)

在变量new_url中,我们将有新的查询参数。

参考:http://api.jquery.com/jquery.param/

答案 24 :(得分:0)

是的,我有一个问题,我的查询字符串会溢出并重复,但这是由于我自己的迟缓。所以我玩了一些并且编写了一些js jquery(实际上是sizzle)和C#magick。

所以我刚才意识到,在服务器完成传递的值之后,值不再重要,没有重用,如果客户端想要做同样的事情,显然它总是一个新的请求,甚至如果它传递相同的参数。这就是所有客户端,所以一些缓存/ cookie等在这方面可能很酷。

JS:

$(document).ready(function () {
            $('#ser').click(function () {
                SerializeIT();
            });
            function SerializeIT() {
                var baseUrl = "";
                baseUrl = getBaseUrlFromBrowserUrl(window.location.toString());
                var myQueryString = "";
                funkyMethodChangingStuff(); //whatever else before serializing and creating the querystring
                myQueryString = $('#fr2').serialize();
                window.location.replace(baseUrl + "?" + myQueryString);
            }
            function getBaseUrlFromBrowserUrl(szurl) {
                return szurl.split("?")[0];
            } 
            function funkyMethodChangingStuff(){
               //do stuff to whatever is in fr2
            }
        });

HTML:

<div id="fr2">
   <input type="text" name="qURL" value="http://somewhere.com" />
   <input type="text" name="qSPart" value="someSearchPattern" />
</div>
<button id="ser">Serialize! and go play with the server.</button>

C#:

    using System.Web;
    using System.Text;
    using System.Collections.Specialized;

    public partial class SomeCoolWebApp : System.Web.UI.Page
    {
        string weburl = string.Empty;
        string partName = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string loadurl = HttpContext.Current.Request.RawUrl;
            string querySZ = null;
            int isQuery = loadurl.IndexOf('?');
            if (isQuery == -1) { 
                //If There Was no Query
            }
            else if (isQuery >= 1) {
                querySZ = (isQuery < loadurl.Length - 1) ? loadurl.Substring(isQuery + 1) : string.Empty;
                string[] getSingleQuery = querySZ.Split('?');
                querySZ = getSingleQuery[0];

                NameValueCollection qs = null;
                qs = HttpUtility.ParseQueryString(querySZ);

                weburl = qs["qURL"];
                partName = qs["qSPart"];
                //call some great method thisPageRocks(weburl,partName); or whatever.
          }
      }
  }
  

欢迎批评(这是一个夜间混合,所以请随意注意调整)。如果这有帮助的话,请大家注意,Happy Coding。

没有重复项,每个请求都是您修改后唯一的,并且由于结构的原因,很容易从dom中动态添加更多查询。

答案 25 :(得分:0)

用于查找特定查询字符串并替换其值*

的Java脚本代码
('input.letter').click(function () {
                //0- prepare values
                var qsTargeted = 'letter=' + this.value; //"letter=A";
                var windowUrl = '';
                var qskey = qsTargeted.split('=')[0];
                var qsvalue = qsTargeted.split('=')[1];
                //1- get row url
                var originalURL = window.location.href;
                //2- get query string part, and url
                if (originalURL.split('?').length > 1) //qs is exists
                {
                    windowUrl = originalURL.split('?')[0];
                    var qs = originalURL.split('?')[1];
                    //3- get list of query strings
                    var qsArray = qs.split('&');
                    var flag = false;
                    //4- try to find query string key
                    for (var i = 0; i < qsArray.length; i++) {
                        if (qsArray[i].split('=').length > 0) {
                            if (qskey == qsArray[i].split('=')[0]) {
                                //exists key
                                qsArray[i] = qskey + '=' + qsvalue;
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (!flag)//   //5- if exists modify,else add
                    {
                        qsArray.push(qsTargeted);
                    }
                    var finalQs = qsArray.join('&');
                    //6- prepare final url
                    window.location = windowUrl + '?' + finalQs;
                }
                else {
                    //6- prepare final url
                    //add query string
                    window.location = originalURL + '?' + qsTargeted;
                }
            })
        });

答案 26 :(得分:0)

这是我做练习时略有不同的方法

function addOrChangeParameters( url, params )
{
  let splitParams = {};
  let splitPath = (/(.*)[?](.*)/).exec(url);
  if ( splitPath && splitPath[2] )
    splitPath[2].split("&").forEach( k => { let d = k.split("="); splitParams[d[0]] = d[1]; } );
  let newParams = Object.assign( splitParams, params );
  let finalParams = Object.keys(newParams).map( (a) => a+"="+newParams[a] ).join("&");
  return splitPath ? (splitPath[1] + "?" + finalParams) : (url + "?" + finalParams);
}

用法:

const url = "http://testing.com/path?empty&value1=test&id=3";

addOrChangeParameters( url, {value1:1, empty:"empty", new:0} )

"http://testing.com/path?empty=empty&value1=1&id=3&new=0"

答案 27 :(得分:0)

到2020年年底,由于现代javascript,node.js和浏览器的支持,我们可以摆脱第三方库漩涡(jquery,查询字符串等)并自行进行干燥。

以下是用于添加或更新给定url的查询参数的函数的javascript(node.js)和打字稿版本:

Javascript

const getUriWithParam = (baseUrl, params) => {
  const Url = new URL(baseUrl);
  let urlParams = new URLSearchParams(Url.search);
  for (const key in params) {
    if (params[key] !== undefined) {
      urlParams.set(key, params[key]);
    }
  }
  Url.search = urlParams.toString();
  return Url.toString();
};

console.info('expected: https://example.com/?foo=bar');
console.log(getUriWithParam("https://example.com", {foo: "bar"}));

console.info('expected: https://example.com/slug?foo=bar#hash');
console.log(getUriWithParam("https://example.com/slug#hash", {foo: "bar"}));

console.info('expected: https://example.com/?bar=baz&foo=bar');
console.log(getUriWithParam("https://example.com?bar=baz", {foo: "bar"}));

console.info('expected: https://example.com/?foo=baz&bar=baz');
console.log(getUriWithParam("https://example.com?foo=bar&bar=baz", {foo: "baz"}));

打字稿

type RequestParamType = {
  [key: string]: any;
};

const getUriWithParam = (
  baseUrl: string,
  params: RequestParamType
): string => {
  const Url = new URL(baseUrl);
  let urlParams: URLSearchParams = new URLSearchParams(Url.search);
  for (const key in params) {
    if (params[key] !== undefined) {
      urlParams.set(key, params[key]);
    }
  }
  Url.search = urlParams.toString();
  return Url.toString();
};

答案 28 :(得分:0)

这个答案只是对 ellemayo's 答案的一个小调整。它会自动更新 URL 而不是仅仅返回更新后的字符串。

function _updateQueryString(key, value, url) {
    if (!url) url = window.location.href;

    let updated = ''
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            updated = url.replace(re, '$1' + key + "=" + value + '$2$3');
        } 
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            updated = url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            updated = url;
        }
        else {
            updated = url;
        }
    }

    window.history.replaceState({ path: updated }, '', updated);
}

答案 29 :(得分:0)

根据Gal和tradyblix的建议,提供修改window.location.search的代码示例:

var qs = window.location.search || "?";
var param = key + "=" + value; // remember to URI encode your parameters
if (qs.length > 1) {
    // more than just the question mark, so append with ampersand
    qs = qs + "&";
}
qs = qs + param;
window.location.search = qs;