Cambiar parámetros de URL


189

Tengo esta URL:

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

lo que necesito es poder cambiar el valor de parámetro de url de 'filas' a algo que especifique, digamos 10. Y si las 'filas' no existen, necesito agregarlo al final de la url y agregar el valor que ya he especificado (10).


2
Una respuesta ligera y sin complementos: stackoverflow.com/a/10997390/11236
— ripper234

11
No puedo creer que sea 2013 y no hay una mejor manera de hacerlo, como algo integrado en las bibliotecas principales del navegador.
— Tyler Collier

Vea mi respuesta para una solución moderna: stackoverflow.com/a/19965480/64949
— Sindre Sorhus

66
@TylerCollier a mediados de 2015 ahora y todavía nada :(
— Tejas Manohar

3
Parece que estamos llegando allí ... developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/…
— Chris

Respuestas:


111

He extendido el código de Sujoy para crear una función.

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

Llamadas de funciones:

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

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

Versión actualizada que también se encarga de los anclajes en la 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;
}

Parece que no puedo hacer que esto funcione. Aquí está mi código: jsfiddle.net/Draven/tTPYL/1 La URL se vería http://www.domain.com/index.php?action=my_action&view-all=Yesy necesito cambiar el valor de "ver todo". Mi pregunta SO que se cerró: stackoverflow.com/questions/13025880/…
— Draven

¿Estás seguro? Me funcionó fácilmente. Compruébalo aquí: jsfiddle.net/mw49a
— Adil Malik

1
Use "var i = 0" en lugar de "i = 0" para evitar crear / modificar i como una variable global.
— Jonathan Aquino

1
Un par de otros problemas con esta función: (1) paramVal no está codificado en uri. (2) si paramVal es nulo, entonces obtienes foo = null. Debería ser foo = (o incluso mejor, eliminar foo por completo).
— Jonathan Aquino

Esto hizo mi vida mucho más fácil. Muchas gracias amigo!
— boydenhartog

97

Creo que quieres el complemento de consulta .

P.ej:

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

Esto funcionará independientemente del estado actual de las filas.


Mofle, eso se debe a que el complemento de consulta utiliza decodeURIComponent y decodeURIComponent ("% F8") no es válido.
— Matthew Flaschen

2
Saca esas cosas raras de tu URL. O, en otras palabras, "cambie su cadena de consulta para usar solo caracteres UTF-8 válidos". :) F8 por sí solo no es un personaje UTF-8 válido.
— Matthew Flaschen

¿Hay alguna manera de recuperar la url base de este complemento? Por ejemplo, si mi URL es ' youtube.com/watch?v=PZootaxRh3M ', obtenga ' youtube.com/watch '
— Matt Norris

3
@Wraith, no necesitas un complemento para eso. Es sólo window.location.pathname.
— Matthew Flaschen

2
@MattNorris No necesita un complemento para esto, pero la respuesta correcta es: window.location.host + window.location.pathname En su caso será "www.youtube.com/watch"
— nktssh

68

Para responder mi propia pregunta 4 años después, después de haber aprendido mucho. Especialmente que no deberías usar jQuery para todo. He creado un módulo simple que puede analizar / stringificar una cadena de consulta. Esto facilita la modificación de la cadena de consulta.

Puede usar query-string de la siguiente manera:

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

1
Wow, esta es una solución brillantemente simple. ¡Gracias!
— jetlej

¡Esto funciona como un campeón! Gracias Sindre 🏆🏆🏆 (todo lo que tienes que hacer es minificar "query-string / index.js" y pegarlo en la parte inferior de tu js)
— Ronnie Royston

1
Tener una biblioteca extra solo por eso parece un poco más ...
— The Godfather

jQuery era demasiado para 1 función, así que en su lugar usaste mecanografiado, travis y varias otras dependencias que no son de desarrollo :)
— Justin Meiners

@JustinMeiners Por favor no comente si no tiene nada útil para contribuir a la conversación. TypeScript no es utilizado por este proyecto. Travis es un CI, no una dependencia.
— Sindre Sorhus

64

Pequeña solución rápida en js puro, no se necesitan complementos:

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

Llámalo así:

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

O, si desea permanecer en la misma página y reemplazar varios parámetros:

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

edición, gracias Lucas: Para eliminar el parámetro del todo, pasar falseo nullpara el valor: replaceQueryParam('rows', false, params). Como 0 también es falso , especifique '0'.


2
también para eliminar un parámetro usado de la salida haga esto: str = replaceQueryParam ('oldparam', false, str) - básicamente ponga un valor de tipo falso
— Luke Wenke

1
tiene un problema, la duplicación de mi parámetro sin una buena razón, consulte esta solución similar stackoverflow.com/a/20420424/3160597
— azerafati

@Bludream ese código ha estado trabajando en producción durante años. Todavía no lo he visto duplicar un parámetro. ¿Puedes publicar una reproducción o alguna información más constructiva?
— bronson

@Bludream Ahora entiendo, es el script al que vinculaste que estaba agregando parámetros duplicados. :)
— bronson

1
@dVyper correcto, un valor falso elimina el parámetro por completo. Use el texto '0' en lugar del entero 0.
— bronson

62

Ben Alman tiene un buen plugin jquery querystring / url aquí que le permite manipular la cadena de consulta fácilmente.

Según lo solicitado

Ir a su página de prueba aquí

En firebug ingrese lo siguiente en la consola

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

Le devolverá la siguiente cadena de URL modificada

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

Observe que el valor de una cadena de consulta para a ha cambiado de X a 3 y ha agregado el nuevo valor.

Luego puede usar la nueva cadena de url como lo desee, por ejemplo, usando document.location = newUrl o cambiar un enlace de anclaje, etc.


44
¿No es jQuery.param.querystring en lugar de jQuery.queryString?
— Petr Peller el

12
TypeError: jQuery.param.querystring is not a function
— TMS

1
Para evitar 'TypeError' debería ser: jQuery.queryString (window.location.href, 'a = 3 & newValue = 100')
— code-gijoe

2
debe llamar jQuery.param.querystring. Supongo que han refactorizado la biblioteca.
— Will Wu

Ninguna de estas funciones existe más. Desea actualizar window.location.search manualmente. Se vuelve más difícil si no desea que la página se vuelva a pintar, ya que esto provocará un cambio de página.
— monokrome

39

Un enfoque moderno para esto es utilizar URLSearchParams basados ​​en estándares nativos . Es compatible con todos los principales navegadores, excepto IE, donde están disponibles polyfills

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.

1
Sería realmente agradable ... pero no es así, ya que IE no lo admite en absoluto, y el uso de polyfills para una cosa tan pequeña está totalmente fuera de discusión.
— forsberg

1
esto también codifica los parámetros originales de la cadena completa, por lo que el resultado parece site.fwx%3Fposition=1&archiveid=5000&columns=5&rows=10&sorting=ModifiedTimeAscconfuso porque no es lo que habría construido si lo hubiera hecho manualmente ...
— Ben Wheeler

1
Sería bueno ver un ejemplo de cómo usarlo. Quiero decir, cómo obtener una cadena de parámetros de la página actual y cómo configurarla después
— The Godfather

27

puedes hacerlo a través de JS normal también

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;

¡Agradable! Tomé esto y lo modifiqué en una función. Envía la url actual, el nombre del parámetro que está buscando, el nuevo valor y un bool que le dice si desea agregar el parámetro a la cadena de consulta si no lo encuentro allí actualmente. La función devuelve la url modificada.
— Gromer

Gormer, debes compartir esa función con otros :)
— Adil Malik

Fragmento impresionante. Yo también lo convertí en una función para mi propio caso de uso. ¡Gracias por compartir! +1
— robabby

19

Esta es la forma moderna de cambiar los parámetros de 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);
  }
}

2
Actualmente, esta solución no es compatible con Internet Explorer 11: caniuse.com/#search=URLSearchParams
— WoIIe

La misma respuesta fue respondida medio año antes que usted por @Alister
— FantomX1

10

¿Sería una alternativa viable a la manipulación de cadenas establecer un html? form y simplemente modificar el valor del rowselemento?

Entonces, con htmleso es algo como

<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 el siguiente JavaScript para enviar el formulario

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

Probablemente no sea adecuado para todas las situaciones, pero podría ser mejor que analizar la cadena de URL.


Esa es una inteligente.
— icarito

7

Puede usar esta mi biblioteca para hacer el trabajo: 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);

4

Solución 2020 : establece la variable o la elimina si pasa nullo undefinedal valor.

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

Tenga en cuenta que URLSearchParamsno funciona en las últimas versiones de todos los principales navegadores (2020)
— Oliver Schimmer


Es compatible con todos los principales navegadores, excepto IE11: caniuse.com/#search=URLSearchParams
— Luis Paulo Lohmann

Incluso si comenzó a ser compatible, la misma respuesta con URLSearchParams fue respondida en esta pregunta al menos 3 veces ya respondida el 15 de enero de 17 a las 15:24, respondió el 14 de junio de 18 a las 15:54 y respondió el 1 de marzo de 19 a las 12:46, como si ninguno de ustedes estuviera leyendo respuestas antes de publicar
— FantomX1

Todas las publicaciones tienen problemas menores que deben resolverse. así que deja que los usuarios voten y elijan el mejor.
— Alper Ebicoglu

3

Escribí una pequeña función auxiliar que funciona con cualquier selección. Todo lo que necesita hacer es agregar la clase "redirectOnChange" a cualquier elemento de selección, y esto hará que la página se vuelva a cargar con un parámetro de cadena de consulta nuevo / modificado, igual a la identificación y el valor de la selección, por ejemplo:

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

El ejemplo anterior agregaría "? MyValue = 222" o "? MyValue = 333" (o usando "&" si existen otros parámetros), y vuelva a cargar la página.

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

Con mucho, la mejor solución en esta página
— ed209

2

Aquí tomé la respuesta de Adil Malik y solucioné los 3 problemas que identifiqué.

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

1

Esto es lo que hago. Usando mi función editParams (), puede agregar, eliminar o cambiar cualquier parámetro, luego usar la función incorporada replaceState () para actualizar la 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;
}

¿Un voto negativo sin comentario? ¿Qué tiene de malo el código? Funciona fantástico para muchas situaciones.
— Bobb Fwed

1

Mi solución:

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

Luego simplemente llame a "setParams" y pase un objeto con los datos que desea configurar.

Ejemplo:

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

En mi caso, tuve que actualizar una entrada de selección html cuando cambia y si el valor es "0", elimine el parámetro. Puede editar la función y eliminar el parámetro de la url si la clave del objeto también es "nula".

Espero que esto ayude a todos


Ya hay 2 respuestas iguales con URLSearchParams antes que ustedes, como si ninguno de ustedes realmente leyera las respuestas. Publicado el 15 de enero de 2017 a las 15:24, respondido el 14 de junio de 18 a las 15:54
— FantomX1

0

Otra variación de la respuesta de Sujoy. Solo cambié los nombres de las variables y agregué un contenedor de espacio de nombres:

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

El uso es ahora:

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

0

Yo también he escrito una biblioteca para obtener y configurar parámetros de consulta de URL en JavaScript .

Aquí hay un ejemplo de su uso.

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

Obtenga parámetros de consulta como un objeto, por clave, o agregue / cambie / elimine.

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


-1

Sé que esta es una vieja pregunta. He mejorado la función anterior para agregar o actualizar parámetros de consulta. Todavía es una solución pura de JS solamente.

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

-1

mi función admite la eliminación de 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(/\&$/, ''));
    }

-1

Acabo de escribir un módulo simple para tratar de leer y actualizar los parámetros de consulta de URL actuales.

Ejemplo de uso:

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]

Aquí está mi código llamado 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 }

Ya hay 4 respuestas similares a las que mencionaste publicadas, respondidas el 15 de enero de 17 a las 15:24, respondidas el 14 de junio de 18 a las 15:54, respondidas el 1 de marzo de 19 a las 12:46 y respondidas el 14 de junio de 19 a las 7: 20, como si realmente nadie de ustedes leyera las respuestas antes de publicar
— FantomX1

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

     });
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.