Come ottenere la stringa di query dall'URL corrente con JavaScript?


108

Ho un URL come questo:

http://localhost/PMApp/temp.htm?ProjectID=462

Quello che devo fare è ottenere i dettagli dopo il ?segno (stringa di query), ovvero ProjectID=462. Come posso ottenerlo utilizzando JavaScript?

Quello che ho fatto finora è questo:

var url = window.location.toString();
url.match(?);

Non so cosa fare dopo.



@ Cupcake: Quella domanda riguarda l'estrazione dei parametri, qui si tratta solo di ottenerelocation.search
Bergi

Votando per riaprire, il duplicato contrassegnato è una richiesta per una libreria, mentre questa domanda riguarda l'ottenimento del codice js.
1615903


Risposte:


239

Dai un'occhiata all'articolo MDN su window.location.

QueryString è disponibile in window.location.search.

Soluzione che funziona anche nei browser legacy

MDN fornisce un esempio (non più disponibile nell'articolo di cui sopra) di come ottenere il valore di una singola chiave disponibile in QueryString. Qualcosa come questo:

function getQueryStringValue (key) {  
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would write the value of the QueryString-variable called name to the console  
console.log(getQueryStringValue("name")); 

Nei browser moderni

Nei browser moderni hai la searchParamsproprietà dell'interfaccia URL, che restituisce un oggetto URLSearchParams . L'oggetto restituito ha una serie di metodi convenienti, incluso un metodo get. Quindi l'equivalente dell'esempio precedente sarebbe:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

L' interfaccia URLSearchParams può essere utilizzata anche per analizzare le stringhe in un formato querystring e trasformarle in un pratico oggetto URLSearchParams.

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

Si noti che il supporto del browser è ancora limitato su questa interfaccia, quindi se è necessario supportare browser legacy, attenersi al primo esempio o utilizzare un polyfill .


Solo una nota: usa sempre al encodeURIComponent/decodeURIComponentposto diescape/unescape
tsh

1
La prima funzione getQueryStringValueper i browser precedenti, non funziona per ?foo=bar&foo1=bar1 Se proviamo a recuperare il valore per foo, restituisce empty string.
Farhan Chauhan

I vecchi browser (IE) possono utilizzare il polyfill per URLSearchParams
Pratyush

@Pratyush sì, lo menziono nella risposta, con un riferimento al pacchetto url-search-params-polyfill più popolare e più aggiornato .
Christofer Eliasson

57

Utilizzare window.location.searchper ottenere tutto dopo aver ? incluso?

Esempio:

var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case

15
O ancora più semplice:let querystring = window.location.search.substring(1);
olibre

15
decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})

Brillante! Molte grazie.
Ron16

Buon approccio. Grazie. Un po 'risolverlo: sostituire controlla l'intera stringa (!). dobbiamo rimuovere il primo carattere. rimuovere i loop non necessari. Risultato: window.location.search window.location.search.substr (1) .split ("&") .reduce ((acc, param) => {const [key, value] = param.split ("=") ; return {... acc, [key]: value};}, {})
Nikita

7

Ciò aggiungerà una funzione globale per accedere alle variabili queryString come mappa.

// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to 'window.location.search'.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
    window.location.query = function (source) {
        var map = {};
        source = source || this.search;

        if ("" != source) {
            var groups = source, i;

            if (groups.indexOf("?") == 0) {
                groups = groups.substr(1);
            }

            groups = groups.split("&");

            for (i in groups) {
                source = groups[i].split("=",
                    // For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
                    (groups[i].slice(-1) !== "=") + 1
                );

                // Key
                i = decodeURIComponent(source[0]);

                // Value
                source = source[1];
                source = typeof source === "undefined"
                    ? source
                    : decodeURIComponent(source);

                // Save Duplicate Key
                if (i in map) {
                    if (Object.prototype.toString.call(map[i]) !== "[object Array]") {
                        map[i] = [map[i]];
                    }

                    map[i].push(source);
                }

                // Save New Key
                else {
                    map[i] = source;
                }
            }
        }

        return map;
    }

    window.location.query.makeString = function (source, addQuestionMark) {
        var str = "", i, ii, key;

        if (typeof source == "boolean") {
            addQuestionMark = source;
            source = undefined;
        }

        if (source == undefined) {
            str = window.location.search;
        }
        else {
            for (i in source) {
                key = "&" + encodeURIComponent(i);

                if (Object.prototype.toString.call(source[i]) !== "[object Array]") {
                    str += key + addUndefindedValue(source[i]);
                }
                else {
                    for (ii = 0; ii < source[i].length; ii++) {
                        str += key + addUndefindedValue(source[i][ii]);
                    }
                }
            }
        }

        return (addQuestionMark === false ? "" : "?") + str.substr(1);
    }

    function addUndefindedValue(source) {
        return typeof source === "undefined"
            ? ""
            : "=" + encodeURIComponent(source);
    }
}

Godere.


5

Se ti è capitato di usare Typescript e hai dom nella tua libreria di tsconfig.json, puoi fare:

const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');

// To append, you can also leverage api to avoid the `?` check 
params.append('newKey', 'newValue');

4

Puoi usare questa funzione per dividere la stringa da? Id =

 function myfunction(myvar){
  var urls = myvar;
  var myurls = urls.split("?id=");
  var mylasturls = myurls[1];
  var mynexturls = mylasturls.split("&");
  var url = mynexturls[0];
  alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");

ecco il violino


4

Puoi usarlo per trovare direttamente il valore tramite il nome del parametro.

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');


2

È possibile utilizzare la searchproprietà window.locationdell'oggetto per ottenere la parte di query dell'URL. Nota che include il punto interrogativo (?) All'inizio, nel caso in cui ciò influisca sul modo in cui intendi analizzarlo.



2
  var queryObj = {};
   if(url.split("?").length>0){
     var queryString = url.split("?")[1];
   }

ora hai la parte query in queryString

La prima sostituzione rimuoverà tutti gli spazi bianchi, la seconda sostituirà tutta la parte "&" con "," e infine la terza sostituzione inserirà ":" al posto dei segni "=".

queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

Supponiamo quindi di avere una query come abc = 123 & efg = 456 . Ora, prima dell'analisi, la tua query viene convertita in qualcosa come {"abc": "123", "efg": "456"}. Ora, quando lo analizzerai, ti darà la tua query nell'oggetto json.


Sebbene questo codice possa rispondere alla domanda, fornire un contesto aggiuntivo su come e / o perché risolve il problema migliorerebbe il valore a lungo termine della risposta.
Badacadabra

2

Converti quello in array e poi dividi con "?"

var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';

url.split('?')[1];     //ProjectID=462


0

Prova questo

/**
 * Get the value of a querystring
 * @param  {String} field The field to get the value of
 * @param  {String} url   The URL to get the value from (optional)
 * @return {String}       The field value
 */
var getQueryString = function ( field, url ) {
    var href = url ? url : window.location.href;
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;
};

Supponiamo che il tuo URL sia http: //example.com&this=chicken&that=sandwich . Vuoi ottenere il valore di questo, quello e un altro.

var thisOne = getQueryString('this'); // returns 'chicken'
var thatOne = getQueryString('that'); // returns 'sandwich'
var anotherOne = getQueryString('another'); // returns null

Se vuoi usare un URL diverso da quello nella finestra, puoi passarne uno come secondo argomento.

var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something'

Riferimento


0

Penso che sia molto più sicuro fare affidamento sul browser rispetto a qualsiasi geniale regex:

const parseUrl = function(url) { 
  const a = document.createElement('a')
  a.href = url
  return {
    protocol: a.protocol ? a.protocol : null,
    hostname: a.hostname ? a.hostname : null,
    port: a.port ? a.port : null,
    path: a.pathname ? a.pathname : null,
    query: a.search ? a.search : null,
    hash: a.hash ? a.hash : null,
    host: a.host ? a.host : null  
  }
}

console.log( parseUrl(window.location.href) ) //stacksnippet
//to obtain a query
console.log( parseUrl( 'https://example.com?qwery=this').query )

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.