Change URL parameters

前端 未结 26 2200
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:40

I have this URL:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

what I need is to be able to

相关标签:
26条回答
  • 2020-11-22 08:54

    Quick little solution in pure js, no plugins needed:

    function replaceQueryParam(param, newval, search) {
        var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
        var query = search.replace(regex, "$1").replace(/&$/, '');
    
        return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
    }
    

    Call it like this:

     window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
    

    Or, if you want to stay on the same page and replace multiple params:

     var str = window.location.search
     str = replaceQueryParam('rows', 55, str)
     str = replaceQueryParam('cols', 'no', str)
     window.location = window.location.pathname + str
    

    edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.

    0 讨论(0)
  • 2020-11-22 08:56

    To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.

    You can use query-string as follows:

    // parse the query string into an object
    var q = queryString.parse(location.search);
    // set the `row` property
    q.rows = 10;
    // convert the object to a query string
    // and overwrite the existing query string
    location.search = queryString.stringify(q);
    
    0 讨论(0)
  • 2020-11-22 08:56

    I just wrote a simple module to deal with reading and updating the current url query params.

    Example usage:

    import UrlParams from './UrlParams'
    
    UrlParams.remove('foo') //removes all occurences of foo=?
    UrlParams.set('foo', 'bar') //set all occurences of foo equal to bar
    UrlParams.add('foo', 'bar2') //add bar2 to foo result: foo=bar&foo=bar2
    UrlParams.get('foo') //returns bar
    UrlParams.get('foo', true) //returns [bar, bar2]
    

    Here is my code named UrlParams.(js/ts):

    class UrlParams {
    
        /**
         * Get params from current url
         * 
         * @returns URLSearchParams
         */
        static getParams(){
            let url = new URL(window.location.href)
            return new URLSearchParams(url.search.slice(1))
        }
    
        /**
         * Update current url with params
         * 
         * @param params URLSearchParams
         */
        static update(params){
            if(`${params}`){
                window.history.replaceState({}, '', `${location.pathname}?${params}`)
            } else {
                window.history.replaceState({}, '', `${location.pathname}`)
            }
        }
    
        /**
         * Remove key from url query
         * 
         * @param param string
         */
        static remove(param){
            let params = this.getParams()
            if(params.has(param)){
                params.delete(param)
                this.update(params)
            }
        }
    
        /**
         * Add key value pair to current url
         * 
         * @param key string
         * @param value string
         */
        static add(key, value){
            let params = this.getParams()
            params.append(key, value)
            this.update(params)
        }
    
        /**
         * Get value or values of key
         * 
         * @param param string
         * @param all string | string[]
         */
        static get(param, all=false){
            let params = this.getParams()
            if(all){
                return params.getAll(param)
            }
            return params.get(param)
        }
    
        /**
         * Set value of query param
         * 
         * @param key string
         * @param value string
         */
        static set(key, value){
            let params = this.getParams()
            params.set(key, value)
            this.update(params)
        }
    
    }
    export default UrlParams
    export { UrlParams }
    
    0 讨论(0)
  • 2020-11-22 08:57

    I too have written a library for getting and setting URL query parameters in JavaScript.

    Here is an example of its usage.

    var url = Qurl.create()
      , query
      , foo
      ;
    

    Get query params as an object, by key, or add/change/remove.

    // returns { foo: 'bar', baz: 'qux' } for ?foo=bar&baz=qux
    query = url.query();
    
    // get the current value of foo
    foo = url.query('foo');
    
    // set ?foo=bar&baz=qux
    url.query('foo', 'bar');
    url.query('baz', 'qux');
    
    // unset foo, leaving ?baz=qux
    url.query('foo', false); // unsets foo
    
    0 讨论(0)
  • 2020-11-22 08:59

    Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:

    window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
    
    
    // background functions below:
    
    // add/change/remove URL parameter
    // use a value of false to remove parameter
    // returns a url-style string
    function editParams (key, value) {
      key = encodeURI(key);
    
      var params = getSearchParameters();
    
      if (Object.keys(params).length === 0) {
        if (value !== false)
          return '?' + key + '=' + encodeURI(value);
        else
          return '';
      }
    
      if (value !== false)
        params[key] = encodeURI(value);
      else
        delete params[key];
    
      if (Object.keys(params).length === 0)
        return '';
    
      return '?' + $.map(params, function (value, key) {
        return key + '=' + value;
      }).join('&');
    }
    
    // Get object/associative array of URL parameters
    function getSearchParameters () {
      var prmstr = window.location.search.substr(1);
      return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
    }
    
    // convert parameters from url-style string to associative array
    function transformToAssocArray (prmstr) {
      var params = {},
          prmarr = prmstr.split("&");
    
      for (var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
      }
      return params;
    }
    
    0 讨论(0)
  • 2020-11-22 08:59

    I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.

                          function addOrUpdateQueryParam(param, newval, search) {
    
                            var questionIndex = search.indexOf('?');
    
                            if (questionIndex < 0) {
                                search = search + '?';
                                search = search + param + '=' + newval;
                                return search;
                            }
    
                            var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
                            var query = search.replace(regex, "$1").replace(/&$/, '');
    
                            var indexOfEquals = query.indexOf('=');
    
                            return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
                        }
    
    0 讨论(0)
提交回复
热议问题