用javascript我怎么能添加一个查询字符串参数的url,如果不存在或如果它存在,更新当前值?我使用jquery为我的客户端开发。


当前回答

更新(2020):URLSearchParams现在被所有现代浏览器支持。

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的赋值会导致页面加载,所以如果这不是理想的,使用历史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);
}

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

然而,浏览器对它的支持很差,因为它目前还处于试验阶段,只在最新版本的Chrome、Firefox、Safari、iOS Safari、Android浏览器、Android Chrome和Opera中使用。如果你决定使用它,使用一个填充。

其他回答

一种不使用正则表达式的不同方法。支持url末尾的“散列”锚以及多个问号字符(?)。应该比正则表达式方法略快。

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
}

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

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

感谢现代javascript, node.js和浏览器的支持,我们可以摆脱第三方库的漩涡(jquery, query-string等)和DRY自己。

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

Javascript

const getUriWithParam = (baseUrl, params) => { const Url = new URL(baseUrl); const 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"}));

打印稿


const getUriWithParam = (
  baseUrl: string,
  params: Record<string, any>
): string => {
  const Url = new URL(baseUrl);
  const 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();
};

对于React Native

URL在React Native中没有实现。所以你必须事先安装react-native-url-polyfill。

对于对象参数

请看这个答案中的第二个解决方案

我想要的是:

使用浏览器的本地URL API 可以添加、更新、获取或删除吗 期望在散列之后的查询字符串,例如对于单页应用程序

function queryParam(options = {}) { var defaults = { method: 'set', url: window.location.href, key: undefined, value: undefined, } for (var prop in defaults) { options[prop] = typeof options[prop] !== 'undefined' ? options[prop] : defaults[prop] } const existing = (options.url.lastIndexOf('?') > options.url.lastIndexOf('#')) ? options.url.substr(options.url.lastIndexOf('?') + 1) : '' const query = new URLSearchParams(existing) if (options.method === 'set') { query.set(options.key, options.value) return `${options.url.replace(`?${existing}`, '')}?${query.toString()}` } else if (options.method === 'get') { const val = query.get(options.key) let result = val === null ? val : val.toString() return result } else if (options.method === 'delete') { query.delete(options.key) let result = `${options.url.replace(`?${existing}`, '')}?${query.toString()}` const lastChar = result.charAt(result.length - 1) if (lastChar === '?') { result = `${options.url.replace(`?${existing}`, '')}` } return result } } // Usage: let url = 'https://example.com/sandbox/#page/' url = queryParam({ url, method: 'set', key: 'my-first-param', value: 'me' }) console.log(url) url = queryParam({ url, method: 'set', key: 'my-second-param', value: 'you' }) console.log(url) url = queryParam({ url, method: 'set', key: 'my-second-param', value: 'whomever' }) console.log(url) url = queryParam({ url, method: 'delete', key: 'my-first-param' }) console.log(url) const mySecondParam = queryParam({ url, method: 'get', key: 'my-second-param', }) console.log(mySecondParam) url = queryParam({ url, method: 'delete', key: 'my-second-param' }) console.log(url)

我意识到这个问题已经很老了,而且已经被回答得死去活来了,但我想尝试一下。我试图在这里重新发明轮子,因为我正在使用目前接受的答案和URL片段的错误处理,最近在一个项目中咬我一口。

函数如下。它很长,但它被设计得尽可能有弹性。我想听听缩短/改进它的建议。我为它(或其他类似的函数)组合了一个小型jsFiddle测试套件。如果一个函数可以通过每一个测试,我说它可能就可以运行了。

更新:我遇到了一个很酷的使用DOM解析url的函数,所以我在这里结合了这项技术。它使函数更短,更可靠。感谢函数的作者。

/**
 * 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;
}