How can I add or update a query string parameter?

后端 未结 27 2870
别那么骄傲
别那么骄傲 2020-11-22 02:35

With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development

相关标签:
27条回答
  • 2020-11-22 03:33

    Update (2020): URLSearchParams is now supported by all modern browsers.

    The URLSearchParams utility can be useful for this in combination with window.location.search. For example:

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

    Now foo has been set to bar regardless of whether or not it already existed.

    However, the above assignment to window.location.search will cause a page load, so if that's not desirable use the History API as follows:

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

    Now you don't need to write your own regex or logic to handle the possible existence of query strings.

    However, browser support is poor as it's currently experimental and only in use in recent versions of Chrome, Firefox, Safari, iOS Safari, Android Browser, Android Chrome and Opera. Use with a polyfill if you do decide to use it.

    0 讨论(0)
  • 2020-11-22 03:33

    It's so simple with URLSearchParams, supported in all modern browsers (caniuse).

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

    If you want to modify the existing URL, construct the object like this: new URLSearchParams(window.location.search) and assign the string to window.location.search.

    0 讨论(0)
  • 2020-11-22 03:33

    A different approach without using regular expressions. Supports 'hash' anchors at the end of the url as well as multiple question mark charcters (?). Should be slightly faster than the regular expression approach.

    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
    }
    
    0 讨论(0)
提交回复
热议问题