How can I add or update a query string parameter?

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

    By using jQuery we can do like below

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

    In variable new_url we will have new query parameters.

    Reference: http://api.jquery.com/jquery.param/

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

    I have expanded the solution and combined it with another that I found to replace/update/remove the querystring parameters based on the users input and taking the urls anchor into consideration.

    Not supplying a value will remove the parameter, supplying one will add/update the parameter. If no URL is supplied, it will be grabbed from 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;
            }
        }
    }
    

    Update

    There was a bug when removing the first parameter in the querystring, I have reworked the regex and test to include a fix.

    Second Update

    As suggested by @JarónBarends - Tweak value check to check against undefined and null to allow setting 0 values

    Third Update

    There was a bug where removing a querystring variable directly before a hashtag would lose the hashtag symbol which has been fixed

    Fourth Update

    Thanks @rooby for pointing out a regex optimization in the first RegExp object. Set initial regex to ([?&]) due to issue with using (\?|&) found by @YonatanKarni

    Fifth Update

    Removing declaring hash var in if/else statement

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

    Java script code to find a specific query string and replace its value *

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

    Yeah I had an issue where my querystring would overflow and duplicate, but this was due to my own sluggishness. so I played a bit and worked up some js jquery(actualy sizzle) and C# magick.

    So i just realized that after the server has done with the passed values, the values doesn't matter anymore, there is no reuse, if the client wanted to do the same thing evidently it will always be a new request, even if its the same parameters being passed. And thats all clientside, so some caching/cookies etc could be cool in that regards.

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

    Okay criticism is welcome (this was a nightly concoction so feel free to note adjustments). If this helped at all, thumb it up, Happy Coding.

    No duplicates, each request as unique as you modified it, and due to how this is structured,easy to add more queries dynamicaly from wthin the dom.

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

    There are a lot of awkward and unnecessarily complicated answers on this page. The highest rated one, @amateur's, is quite good, although it has a bit of unnecessary fluff in the RegExp. Here is a slightly more optimal solution with cleaner RegExp and a cleaner replace call:

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

    As an added bonus, if uri is not a string, you won't get errors for trying to call match or replace on something that may not implement those methods.

    And if you want to handle the case of a hash (and you've already done a check for properly formatted HTML), you can leverage the existing function instead of writing a new function containing the same logic:

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

    Or you can make some slight changes to @Adam's otherwise excellent answer:

    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] || '');
      }
    }
    
    0 讨论(0)
  • 2020-11-22 03:14

    This is my preference, and it covers the cases I can think of. Can anyone think of a way to reduce it to a single replace?

    function setParam(uri, key, val) {
        return uri
            .replace(RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
            .replace(/^([^?&]+)&/, "$1?");
    }
    
    0 讨论(0)
提交回复
热议问题