Domanda

Ho questo URL:

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

ciò di cui ho bisogno è di essere in grado di cambiare le "righe" url param valore a qualcosa che avevo specificare, diciamo 10.E se le 'righe' non esiste, ho bisogno di aggiungere alla fine dell'url e aggiungere il valore, e l'ho già specificato (10).

È stato utile?

Soluzione 4

Per rispondere alla mia domanda 4 anni più tardi, dopo aver imparato molto. Soprattutto che non si dovrebbe usare jQuery per tutto. Ho creato un semplice modulo che può analizzare / stringa i una stringa di query. In questo modo è facile modificare la stringa di query.

È possibile utilizzare stringa di query come segue:

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

Altri suggerimenti

ho esteso il codice di Sujoy per compensare una funzione.

/**
 * http://stackoverflow.com/a/10997390/11236
 */
function updateURLParameter(url, param, paramVal){
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";
    if (additionalURL) {
        tempArray = additionalURL.split("&");
        for (var i=0; i<tempArray.length; i++){
            if(tempArray[i].split('=')[0] != param){
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }
    }

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

Funzione Chiamate:

var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');

window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));

Versione aggiornata che anche prendersi cura degli ancoraggi sulla URL.

function updateURLParameter(url, param, paramVal)
{
    var TheAnchor = null;
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";

    if (additionalURL) 
    {
        var tmpAnchor = additionalURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor = tmpAnchor[1];
        if(TheAnchor)
            additionalURL = TheParams;

        tempArray = additionalURL.split("&");

        for (var i=0; i<tempArray.length; i++)
        {
            if(tempArray[i].split('=')[0] != param)
            {
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }        
    }
    else
    {
        var tmpAnchor = baseURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor  = tmpAnchor[1];

        if(TheParams)
            baseURL = TheParams;
    }

    if(TheAnchor)
        paramVal += "#" + TheAnchor;

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

Credo che si desidera che il plug .

per esempio:.

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

Ciò funzionerà indipendentemente dallo stato attuale di righe.

Ben Alman ha una buona jquery querystring/url plugin qui che permette di manipolare la querystring facilmente.

Come richiesto -

Goto sua pagina di prova qui

In firebug, inserire il seguente console

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

Restituirà il seguente modificato la stringa dell'url

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

Notare la querystring valore è stato modificato da X a 3 e ha aggiunto che il nuovo valore.

È quindi possibile utilizzare la nuova stringa dell'url se vuoi e.g utilizzando il documento.posizione = newUrl o modificare un link di ancoraggio ecc

poco Soluzione rapida in js puri, nessun plug-in necessario:

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

chiamare in questo modo:

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

In alternativa, se si vuole rimanere sulla stessa pagina e sostituire più params:

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

modifica, grazie Luca: Per rimuovere il parametro del tutto, passare false o null per il valore: replaceQueryParam('rows', false, params). Dal momento che 0 è anche falsy , specificare '0'.

Un approccio moderno a questo è di uso standard nativo basato URLSearchParams . E 'supportato da tutti i principali browser, ad eccezione di IE dove stanno polyfills disponibili

const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.

è possibile farlo tramite normale JS anche

var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1]; 
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
    if(tempArray[i].indexOf("rows") == -1){
            newAdditionalURL += temp+tempArray[i];
                temp = "&";
            }
        }
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;

sarebbe una valida alternativa alla manipolazione String essere quello di istituire un form html e basta modificare il valore dell'elemento rows?

Così, con html che è qualcosa come

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

Con il seguente JavaScript per inviare il modulo

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

Probabilmente non adatto a tutte le situazioni, ma potrebbe essere più bello di parsing della stringa URL.

Questo è il modo moderno di modificare i parametri URL:

function setGetParam(key,value) {
  if (history.pushState) {
    var params = new URLSearchParams(window.location.search);
    params.set(key, value);
    var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.toString();
    window.history.pushState({path:newUrl},'',newUrl);
  }
}

È possibile utilizzare questa mia biblioteca per fare il lavoro: https://github.com/Mikhus/jsurl

var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);

ho scritto un po 'di funzione di supporto che funziona con qualsiasi select. Tutto quello che dovete fare è aggiungere la classe "redirectOnChange" a qualsiasi elemento di selezione, e questo farà sì che nella pagina di ricaricare con un parametro nuovo / cambiato querystring, pari al id e il valore della selezione, per esempio:

<select id="myValue" class="redirectOnChange"> 
    <option value="222">test222</option>
    <option value="333">test333</option>
</select>

L'esempio riportato sopra dovrebbe aggiungere "? MyValue = 222" o "? MyValue = 333" (o usando "&" se esistono altri params), e ricaricare la pagina.

jQuery:

$(document).ready(function () {

    //Redirect on Change
    $(".redirectOnChange").change(function () {
        var href = window.location.href.substring(0, window.location.href.indexOf('?'));
        var qs = window.location.href.substring(window.location.href.indexOf('?') + 1, window.location.href.length);
        var newParam = $(this).attr("id") + '=' + $(this).val();

        if (qs.indexOf($(this).attr("id") + '=') == -1) {
            if (qs == '') {
                qs = '?'
            }
            else {
                qs = qs + '&'
            }
            qs = qs + newParam;

        }
        else {
            var start = qs.indexOf($(this).attr("id") + "=");
            var end = qs.indexOf("&", start);
            if (end == -1) {
                end = qs.length;
            }
            var curParam = qs.substring(start, end);
            qs = qs.replace(curParam, newParam);
        }
        window.location.replace(href + '?' + qs);
    });
});

Qui ho preso la risposta di Adil Malik e fissato i 3 numeri che identifica con esso.

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

Un'altra variazione sul risposta di Sujoy. Appena cambiato i nomi delle variabili e aggiunto un wrapper namespace:

window.MyNamespace = window.MyNamespace  || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};

(function (ns) {

    ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {

        var otherQueryStringParameters = "";

        var urlParts = url.split("?");

        var baseUrl = urlParts[0];
        var queryString = urlParts[1];

        var itemSeparator = "";
        if (queryString) {

            var queryStringParts = queryString.split("&");

            for (var i = 0; i < queryStringParts.length; i++){

                if(queryStringParts[i].split('=')[0] != parameterName){

                    otherQueryStringParameters += itemSeparator + queryStringParts[i];
                    itemSeparator = "&";
                }
            }
        }

        var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;

        return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
    };

})(window.MyNamespace.Uri);

Usage è ora:

var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");

Anch'io ho scritto un per ottenere e impostare i parametri di ricerca URL in JavaScript .

Ecco un esempio del suo utilizzo.

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

Come parametri di query come un oggetto, dalla chiave, o aggiungere / modificare / rimuovere.

// 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

Ecco quello che faccio. Usando la mia funzione editParams (), è possibile aggiungere, rimuovere o modificare qualsiasi parametro, quindi utilizzare il costruito nel replaceState () per aggiornare l'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;
}

che stavo cercando la stessa cosa ed ho trovato: https://github.com/medialize/URI. js che è piuttosto bella:)

- Aggiornamento

Ho trovato un pacchetto migliore: https://www.npmjs.org/package/qs si occupa anche di array in get params.

La mia soluzione:

const setParams = (data) => {
    if (typeof data !== 'undefined' && typeof data !== 'object') {
        return
    }

    let url = new URL(window.location.href)
    const params = new URLSearchParams(url.search)

    for (const key of Object.keys(data)) {
        if (data[key] == 0) {
            params.delete(key)
        } else {
            params.set(key, data[key])
        }
    }

    url.search = params
    url = url.toString()
    window.history.replaceState({ url: url }, null, url)
}

Poi basta chiamare "setparams" e passare un oggetto con i dati che si desidera impostare.

Esempio:

$('select').on('change', e => {
    const $this = $(e.currentTarget)
    setParams({ $this.attr('name'): $this.val() })
})

Nel mio caso ho dovuto aggiornare una selezione ingresso html quando cambia e se il valore è "0", rimuovere il parametro. È possibile modificare la funzione e rimuovere il parametro dall'URL se la chiave oggetto è "nullo" pure.

Spero che questo aiuti yall

So che questa è una vecchia questione. Ho migliorato la funzione di cui sopra per aggiungere o query di aggiornamento params. Ancora solo una soluzione pura JS.

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

la mia funzione di supporto rimuovendo param

function updateURLParameter(url, param, paramVal, remove = false) {
        var newAdditionalURL = '';
        var tempArray = url.split('?');
        var baseURL = tempArray[0];
        var additionalURL = tempArray[1];
        var rows_txt = '';

        if (additionalURL)
            newAdditionalURL = decodeURI(additionalURL) + '&';

        if (remove)
            newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
        else
            rows_txt = param + '=' + paramVal;

        window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
    }

Il mio frammento con URI codifica / decodifica:

function isDefined(object) {
	return object !== undefined && object !== null;
}

function isNotEmpty(string) {
	return isDefined(string) && string.length > 0;
}

/**
 * Update or add the specified URL parameter.
 * <p>
 * @param {String} name
 * @param {String} value
 */
function updateUrlParam(name, value) {
	// Get the path and the query
	var urlInfo = decodeURI(window.location.href).split('?');
	var path = urlInfo[0];
	var query = urlInfo[1];

	// Build the query
	var params = '';
	var anchor = null;
	if (isNotEmpty(query)) {
		var queryInfo = query.split('#');
		query = queryInfo[0];
		anchor = queryInfo[1];

		queryInfo = query.split('&');
		for (var i = 0; i < queryInfo.length; ++i) {
			if (queryInfo[i].split('=')[0] !== name) {
				params += '&' + queryInfo[i];
			}
		}
	} else {
		var queryInfo = path.split('#');
		query = queryInfo[0];
		anchor = queryInfo[1];
		if (isNotEmpty(query)) {
			path = query;
		}
	}
	query = '?' + name + '=' + value + params;
	if (isNotEmpty(anchor)) {
		query += '#' + anchor;
	}

	// Replace the URL
	window.history.replaceState('', '', encodeURI(path + query));
}

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

     });

2019 Soluzione : imposta la variabile o rimuove iti se si passa null o undefined al valore

.
var setSearchParam = function(key, value) {
    if (!window.history.pushState) {
        return;
    }

    if (!key) {
        return;
    }

    var url = new URL(window.location.href);
    var params = new window.URLSearchParams(window.location.search);
    if (value === undefined || value === null) {
        params.delete(key);
    } else {
        params.set(key, value);
    }

    url.search = params;
    url = url.toString();
    window.history.replaceState({url: url}, null, url);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top