How can I add or update a query string parameter?

后端 未结 27 2837
别那么骄傲
别那么骄傲 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:24

    Use this function to add, remove and modify query string parameter from URL based on jquery

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

    Add new and modify existing parameter to url

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

    Remove existing

    var new_url = modifyURLQuery("http://google.com?foo=50&bar=45", {bar: null});
    // Result: http://google.com?foo=50
    
    0 讨论(0)
  • 2020-11-22 03:24

    This should serve the purpose:

    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("&");
    }   
    
    0 讨论(0)
  • 2020-11-22 03:25

    If it's not set or want to update with a new value you can use:

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

    This is in simple Javascript, by the way.

    EDIT

    You may want to try using the jquery query-object plugin

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

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

    if you want to set multiple parameters at once:

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

    same function as @amateur's

    if jslint gives you an error add this after the for loop

    if(params.hasOwnProperty(key))
    
    0 讨论(0)
  • 2020-11-22 03:31

    window.location.search is read/write.

    However - modifying the query string will redirect the page you're on and cause a refresh from the server.

    If what you're attempting to do is maintain client side state (and potentially make it bookmark-able), you'll want to modify the URL hash instead of the query string, which keeps you on the same page (window.location.hash is read/write). This is how web sites like twitter.com do this.

    You'll also want the back button to work, you'll have to bind javascript events to the hash change event, a good plugin for that is http://benalman.com/projects/jquery-hashchange-plugin/

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

    I know this is quite old but i want to fires my working version in here.

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

    NOTE This is a modified version of @elreimundo

    0 讨论(0)
提交回复
热议问题