Change URL parameters

前端 未结 26 2204
孤独总比滥情好
孤独总比滥情好 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 09:15

    I think you want the query plugin.

    E.g.:

    window.location.search = jQuery.query.set("rows", 10);
    

    This will work regardless of the current state of rows.

    0 讨论(0)
  • 2020-11-22 09:15

    Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?

    So, with html that is something like

    <form id='myForm' target='site.fwx'>
        <input type='hidden' name='position' value='1'/>
        <input type='hidden' name='archiveid' value='5000'/>
        <input type='hidden' name='columns' value='5'/>
        <input type='hidden' name='rows' value='20'/>
        <input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
    </form>
    

    With the following JavaScript to submit the form

    var myForm = document.getElementById('myForm');
    myForm.rows.value = yourNewValue;
    myForm.submit();
    

    Probably not suitable for all situations, but might be nicer than parsing the URL string.

    0 讨论(0)
  • 2020-11-22 09:15

    Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.

    /**
     * Adds or updates a URL parameter.
     *
     * @param {string} url  the URL to modify
     * @param {string} param  the name of the parameter
     * @param {string} paramVal  the new value for the parameter
     * @return {string}  the updated URL
     */
    self.setParameter = function (url, param, paramVal){
      // http://stackoverflow.com/a/10997390/2391566
      var parts = url.split('?');
      var baseUrl = parts[0];
      var oldQueryString = parts[1];
      var newParameters = [];
      if (oldQueryString) {
        var oldParameters = oldQueryString.split('&');
        for (var i = 0; i < oldParameters.length; i++) {
          if(oldParameters[i].split('=')[0] != param) {
            newParameters.push(oldParameters[i]);
          }
        }
      }
      if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
        newParameters.push(param + '=' + encodeURI(paramVal));
      }
      if (newParameters.length > 0) {
        return baseUrl + '?' + newParameters.join('&');
      } else {
        return baseUrl;
      }
    }
    
    0 讨论(0)
  •      // usage: clear ; cd src/js/node/js-unit-tests/01-set-url-param ; npm test ; cd -
         // prereqs: , nodejs , mocha
         // URI = scheme:[//authority]path[?paramName1=paramValue1&paramName2=paramValue2][#fragment]
         // call by: uri = uri.setUriParam("as","md")
         String.prototype.setUriParam = function (paramName, paramValue) {
            var uri = this
            var fragment = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
            uri = ( uri.indexOf('#') === -1 ) ? uri : uri.split('#')[0]
            if ( uri.indexOf("?") === -1 ) { uri = uri + '?&' }
            uri = uri.replace ( '?' + paramName , '?&' + paramName)
            var toRepl = (paramValue != null) ? ('$1' + paramValue) : ''
            var toSrch = new RegExp('([&]' + paramName + '=)(([^&#]*)?)')
            uri = uri.replace(toSrch,toRepl)
            if (uri.indexOf(paramName + '=') === -1 && toRepl != '' ) {
               var ampersandMayBe = uri.endsWith('&') ? '' : '&'
               uri = uri + ampersandMayBe + paramName + "=" + String(paramValue)
            }
            uri = ( fragment.length == 0 ) ? uri : (uri+"#"+fragment) //may-be re-add the fragment
            return uri
         }
    
         var assert = require('assert');
         describe('replacing url param value', function () {
    
            // scheme://authority/path[?p1=v1&p2=v2#fragment
            // a clean url
            it('http://org.com/path -> http://org.com/path?&prm=tgt_v', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
               var uriActual = uri.setUriParam("bid",10)
               assert.equal(uriActual, uriExpected);
            });
    
            // has the url param existing after the ? with num value
            it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=57'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
               var uriActual = uri.setUriParam("bid",10)
               assert.equal(uriActual, uriExpected);
            });
    
            // has the url param existing after the ? but string value
            it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=boo-bar'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=boo-bar-baz'
               var uriActual = uri.setUriParam("bid","boo-bar-baz")
               assert.equal(uriActual, uriExpected);
            });
    
            // has the url param existing after the ?& but string value
            it('http://org.com/path?&prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
               var uriActual = uri.setUriParam("bid",10)
               assert.equal(uriActual, uriExpected);
            });
    
            // has the url param existing after the ? with other param
            it('http://org.com/path?prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v'
               var uriActual = uri.setUriParam("bid",10)
               assert.equal(uriActual, uriExpected);
            });
    
            // has the url param existing after the ?& with other param
            it('http://org.com/path?&prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v'
               var uriActual = uri.setUriParam("bid",10)
               assert.equal(uriActual, uriExpected);
            });
    
            // has the url param existing after the ? with other param with fragment
            it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v#f'
               var uriActual = uri.setUriParam("bid",10)
               assert.equal(uriActual, uriExpected);
            });
    
            // has the url param existing after the ?& with other param with fragment
            it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v#f'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v#f'
               var uriActual = uri.setUriParam("bid",10)
               assert.equal(uriActual, uriExpected);
            });
    
            // remove the param-name , param-value pair
            it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
               var uriActual = uri.setUriParam("bid",null)
               assert.equal(uriActual, uriExpected);
            });
    
            // remove the param-name , param-value pair
            it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p=other_v#f'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
               var uriActual = uri.setUriParam("bid",null)
               assert.equal(uriActual, uriExpected);
            });
    
            // add a new param name , param value pair
            it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
               var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
               var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v&bid=foo-bar#f'
               var uriActual = uri.setUriParam("bid","foo-bar")
               assert.equal(uriActual, uriExpected);
            });
    
         });
    
    0 讨论(0)
  • 2020-11-22 09:16

    Here is a simple solution using the query-string library.

    const qs = require('query-string')
    function addQuery(key, value) {
      const q = qs.parse(location.search)
      const url = qs.stringifyUrl(
        {
          url: location.pathname,
          query: {
          ...q,
          [key]: value,
          },
        },
        { skipEmptyString: true }
      );
      window.location.href = url
      // if you are using Turbolinks
      // add this: Turbolinks.visit(url)
    }
    // Usage
    addQuery('page', 2)
    

    If you are using react without react-router

    export function useAddQuery() {
      const location = window.location;
      const addQuery = useCallback(
        (key, value) => {
          const q = qs.parse(location.search);
          const url = qs.stringifyUrl(
            {
              url: location.pathname,
              query: {
                ...q,
                [key]: value,
              },
            },
            { skipEmptyString: true }
          );
          window.location.href = url
        },
        [location]
      );
    
      return { addQuery };
    }
    // Usage
    const { addQuery } = useAddQuery()
    addQuery('page', 2)
    

    If you are using react with react-router

    export function useAddQuery() {
      const location = useLocation();
      const history = useHistory();
    
      const addQuery = useCallback(
        (key, value) => {
          let pathname = location.pathname;
          let searchParams = new URLSearchParams(location.search);
          searchParams.set(key, value);
          history.push({
            pathname: pathname,
            search: searchParams.toString()
          });
        },
        [location, history]
      );
    
      return { addQuery };
    }
    
    // Usage
    const { addQuery } = useAddQuery()
    addQuery('page', 2)
    

    PS: qs is the import from query-string module.

    0 讨论(0)
  • 2020-11-22 09:17

    Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.

    As requested -

    Goto his test page here

    In firebug enter the following into the console

    jQuery.param.querystring(window.location.href, 'a=3&newValue=100');

    It will return you the following amended url string

    http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3

    Notice the a querystring value for a has changed from X to 3 and it has added the new value.

    You can then use the new url string however you wish e.g using document.location = newUrl or change an anchor link etc

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