Jak Mogę uzyskać wartości ciągów zapytań w JavaScript?

Odpowiedzi na to pytanie są wysiłkiem Społeczności. Edytuj istniejące odpowiedzi, aby poprawić ten post. Obecnie nie przyjmuje nowych odpowiedzi ani interakcji.

Czy istnieje sposób pobierania zapytania bez wtyczki string wartości poprzez jQuery (lub bez)?

Jeśli tak, to w jaki sposób? Jeśli nie, czy istnieje wtyczka, która może to zrobić?
Author: Ripounet, 2009-05-23

30 answers

Update: Sep-2018

Możesz użyć URLSearchParams, który jest prosty i ma przyzwoitą (ale nie pełną) obsługę przeglądarki.

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

Oryginalny

Nie potrzebujesz jQuery do tego celu. Możesz użyć tylko czystego JavaScript:

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

Użycie:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)

Uwaga: Jeśli parametr jest obecny kilka razy (?foo=lorem&foo=ipsum), otrzymasz pierwszą wartość (lorem). Nie ma na ten temat standardu, a zwyczaje się różnią, zobacz na przykład to pytanie: autorytatywna pozycja zduplikowanych kluczy HTTP GET query .

Uwaga: funkcja uwzględnia wielkość liter. Jeśli preferujesz nazwę parametru niewrażliwego na wielkość liter, dodaj modyfikator " i " do wyrażenia regularnego


Jest to aktualizacja oparta na nowej specyfikacji URLSearchParams , aby uzyskać ten sam wynik bardziej zwięźle. Zobacz odpowiedź zatytułowaną" URLSearchParams " poniżej.

 8752
Author: Code Spy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-03 20:32:10

Niektóre z zamieszczonych tutaj rozwiązań są nieefektywne. Powtarzanie wyszukiwania wyrażeń regularnych za każdym razem, gdy skrypt potrzebuje dostępu do parametru jest całkowicie niepotrzebne, wystarczy jedna funkcja dzielenia parametrów na obiekt w stylu asocjacyjnym-array. Jeśli nie pracujesz z interfejsem HTML 5 History API, jest to konieczne tylko raz na załadowanie strony. Inne sugestie tutaj również nie dekodują poprawnie adresu URL.

var urlParams;
(window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

Przykładowe zapytanie:

?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty

Wynik:

 urlParams = {
    enc: " Hello ",
    i: "main",
    mode: "front",
    sid: "de8d49b78a85a322c4155015fdce22c4",
    empty: ""
}

alert(urlParams["mode"]);
// -> "front"

alert("empty" in urlParams);
// -> true

Można to łatwo ulepszyć, aby również obsługiwać ciągi zapytań w stylu tablicy. Przykładem tego jest tutaj , ale ponieważ parametry w stylu tablicy nie są zdefiniowane w RFC 3986 Nie będę zanieczyszczał tej odpowiedzi kodem źródłowym. dla zainteresowanych wersją "zanieczyszczoną", spójrz na odpowiedź campbeln poniżej.

Również, jak podkreślono w komentarzach, ; jest prawnym ogranicznikiem par key=value. Byłoby wymagaj bardziej skomplikowanego regexu do obsługi ; lub &, który uważam za niepotrzebny, ponieważ rzadko używa się ; i powiedziałbym nawet bardziej nieprawdopodobne, że oba zostaną użyte. Jeśli potrzebujesz wsparcia ; zamiast &, po prostu zamień je w wyrażeniu regularnym.


Jeśli używasz języka wstępnego przetwarzania po stronie serwera, możesz użyć jego natywnych funkcji JSON, aby wykonać ciężkie zadanie. Na przykład w PHP można napisać:
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>
[[14]} Much prostsze!

Zaktualizowano

Nową możliwością byłoby odzyskiwanie powtarzających się paramów w następujący sposób myparam=1&myparam=2. Nie istnieje Specyfikacja , jednak większość obecnych podejść podąża za generowaniem tablicy.

myparam = ["1", "2"]

Tak więc, jest to podejście do zarządzania nim:

let urlParams = {};
(window.onpopstate = function () {
    let match,
        pl = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) {
            return decodeURIComponent(s.replace(pl, " "));
        },
        query = window.location.search.substring(1);

    while (match = search.exec(query)) {
        if (decode(match[1]) in urlParams) {
            if (!Array.isArray(urlParams[decode(match[1])])) {
                urlParams[decode(match[1])] = [urlParams[decode(match[1])]];
            }
            urlParams[decode(match[1])].push(decode(match[2]));
        } else {
            urlParams[decode(match[1])] = decode(match[2]);
        }
    }
})();
 1735
Author: Andy E,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-29 19:20:24

ES2015 (ES6)

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

Bez jQuery

var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

Z adresem URL takim jak ?topic=123&name=query+string, zwróci:

qs["topic"];    // 123
qs["name"];     // query string
qs["nothere"];  // undefined (object)

Metoda Google

Łamiąc Kod Google ' a znalazłem metodę, której używają: getUrlParameters

function (b) {
    var c = typeof b === "undefined";
    if (a !== h && c) return a;
    for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
        var l = b[f][p]("=");
        if (l !== -1) {
            var q = b[f][I](0, l),
                l = b[f][I](l + 1),
                l = l[Ca](/\+/g, " ");
            try {
                d[q] = e(l)
            } catch (A) {}
        }
    }
    c && (a = d);
    return d
}
To jest zaciemnione, ale zrozumiałe. Nie działa, ponieważ niektóre zmienne są niezdefiniowane.

Zaczynają szukać parametrów na url z ?, a także z hash #. Następnie dla każdego parametru dzielą się na znak równości b[f][p]("=") (który wygląda jak indexOf, używają pozycji znaku, aby uzyskać klucz / wartość). Po podziale sprawdzają, czy parametr ma wartość, czy nie, jeśli ma, przechowują wartość d, w przeciwnym razie po prostu kontynuują.

Na końcu zwracany jest obiekt d, obsługujący znaki Escape i +. Ten obiekt jest taki jak mój, zachowuje się tak samo.


Moja metoda jako jQuery plugin

(function($) {
    $.QueryString = (function(paramsArray) {
        let params = {};

        for (let i = 0; i < paramsArray.length; ++i)
        {
            let param = paramsArray[i]
                .split('=', 2);
            
            if (param.length !== 2)
                continue;
            
            params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
        }
            
        return params;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

Użycie

//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"

//Get all params as object
$.QueryString
//This outputs something like...
//Object { param: "val", param2: "val" }

//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object

//Convert object into string suitable for url a querystring (Requires jQuery)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue&param2=val"

//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
history.pushState({}, '', "?" + $.param($.QueryString));

Test wydajności (metoda dzielona z metodą regex) (jsPerf )

Kod przygotowania: deklaracja metod

Podział kodu testu

var qs = window.GetQueryString(query);

var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];

Regex test code

var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");

Testowanie w Firefoksie 4.0 x86 Na Windows Server 2008 R2 / 7 x64

  • metoda podziału: 144,780 ±2.17% najszybszy
  • metoda Regex: 13,891 ±0.85% | 90% wolniej
 1300
Author: BrunoLM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

Ulepszona Wersja Artem Barger ' s answer :

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

Aby uzyskać więcej informacji na temat poprawy patrz: http://james.padolsey.com/javascript/bujs-1-getparameterbyname/

 668
Author: James,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:45

URLSearchParams

W przeciwieństwie do większości przeglądarek internetowych, przeglądarka nie jest w stanie obsługiwać plików cookie.]}

Jest Google-sugerowane URLSearchParams polyfill dla stabilnych wersji IE.

Nie jest standaryzowany przez W3C , ale jest to standard życia przez WhatWG.

Możesz go użyć na location:

const params = new URLSearchParams(location.search);

Lub

const params = (new URL(location)).searchParams;

Lub oczywiście na dowolnym adresie URL:

const url = new URL('https://example.com?foo=1&bar=2');
const params = new URLSearchParams(url.search);

Możesz uzyskać params również używając właściwości .searchParams na obiekcie URL, jak to:

const params = new URL('https://example.com?foo=1&bar=2').searchParams;
params.get('foo'); // "1"
params.get('bar'); // "2" 

Odczytujesz / ustawiasz parametry poprzez get(KEY), set(KEY, VALUE), append(KEY, VALUE) API. Można również iterować nad wszystkimi wartościami for (let p of params) {}.

A implementacja referencyjna i Przykładowa Strona są dostępne dla audyt i testy.

 625
Author: Paul Sweatte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-05 09:52:47

Kolejna rekomendacja. Wtyczka Purl pozwala odzyskać wszystkie części URL, w tym anchor, host, itp.

Może być używany z jQuery lub bez niego.

Użycie jest bardzo proste i fajne:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

Jednak od 11 listopada 2014 r. Purl nie jest już utrzymywany i autor zaleca używanie URI.js zamiast. Wtyczka jQuery różni się tym, że skupia się na elementach - do użycia z ciągami, po prostu użyj URI bezpośrednio, z lub bez jQuery. Podobny kod wyglądałby tak, fuller docs tutaj :

var url = new URI('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.protocol(); // returns 'http'
url.path(); // returns '/folder/dir/index.html'
 400
Author: AlfaTeK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-29 21:05:09

tl; dr

Szybkie, kompletne rozwiązanie , które obsługuje wielowartościowe klucze i zakodowane znaki .

var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {var s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (qd[k] = qd[k] || []).push(v)})

//using ES6   (23 characters cooler)
var qd = {};
if (location.search) location.search.substr(1).split`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})
Wielowarstwowe:
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})

Co to za Kod...
"null-coalescing", ocena zwarcia
ES6 zadania destrukcyjne, funkcje strzałek, ciągi szablonów

Przykład:
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

> qd.a[1]    // "5"
> qd["a"][1] // "5"



Czytaj więcej... o Vanilla JavaScript solution.

aby uzyskać dostęp do różnych części adresu URL location.(search|hash)

Najprostsze (atrapa) rozwiązanie

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
  • obsługuje puste klucze poprawnie.
  • nadpisuje multi-keys z ostatnią wartością znalezioną.
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined

Klucze wielowartościowe

Proste sprawdzenie klucza (item in dict) ? dict.item.push(val) : dict.item = [val]

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {(item.split("=")[0] in qd) ? qd[item.split("=")[0]].push(item.split("=")[1]) : qd[item.split("=")[0]] = [item.split("=")[1]]})
  • teraz zwraca tablice zamiast tego.
  • Access values by qd.key[index] or qd[key][index]
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]

Zakodowane znaki?

Użyj decodeURIComponent() dla drugiegolub obu .

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
Przykład:
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=ståle&car=saab"]



From comments

*!!! proszę zauważyć, że decodeURIComponent(undefined) zwraca łańcuch "undefined". Rozwiązanie polega na prostym użyciu &&, co zapewnia, że decodeURIComponent() nie jest wywoływana na niezdefiniowanych wartościach. (Patrz "kompletne rozwiązanie" na górze.)

v = v && decodeURIComponent(v);


If the querystring jest pusty (location.search == ""), wynik jest nieco mylący qd == {"": undefined}. Przed uruchomieniem funkcji parsowania zaleca się sprawdzenie querystring:

if (location.search) location.search.substr(1).split("&").forEach(...)
 245
Author: Qwerty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-12 08:29:32

Roshambo on snipplr.com ma prosty skrypt, aby to osiągnąć opisany w Pobierz parametry URL z jQuery / ulepszone. Dzięki jego skryptowi można również łatwo wyciągnąć tylko parametry, które chcesz.

Oto sedno sprawy:

$.urlParam = function(name, url) {
    if (!url) {
     url = window.location.href;
    }
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
    if (!results) { 
        return undefined;
    }
    return results[1] || undefined;
}

Następnie pobierz swoje parametry z ciągu zapytania.

Więc jeśli łańcuch URL / zapytania to xyz.com/index.html?lang=de.

Po prostu zadzwoń i masz to.

UZBEKJON ma również świetny wpis na blogu na ten temat, Pobierz adres URL parametry i wartości z jQuery.

 220
Author: brandonjp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-04 18:51:35

Jeśli używasz jQuery, możesz użyć biblioteki, takiej jak jQuery BBQ: Back Button & Query Library .

...jQuery BBQ zapewnia pełną metodę .deparam(), wraz z zarządzaniem stanem hash oraz fragment / query string parse i merge utility methods.

Edit: Dodanie Przykładu:

 var DeparamExample = function() {
            var params = $.deparam.querystring();

            //nameofparam is the name of a param from url
            //code below will get param if ajax refresh with hash
            if (typeof params.nameofparam == 'undefined') {
                params = jQuery.deparam.fragment(window.location.href);
            }
            
            if (typeof params.nameofparam != 'undefined') {
                var paramValue = params.nameofparam.toString();
                  
            }
        };

Jeśli chcesz po prostu użyć zwykłego JavaScript, możesz użyć...

var getParamValue = (function() {
    var params;
    var resetParams = function() {
            var query = window.location.search;
            var regex = /[?&;](.+?)=([^&;]+)/g;
            var match;

            params = {};

            if (query) {
                while (match = regex.exec(query)) {
                    params[match[1]] = decodeURIComponent(match[2]);
                }
            }    
        };

    window.addEventListener
    && window.addEventListener('popstate', resetParams);

    resetParams();

    return function(param) {
        return params.hasOwnProperty(param) ? params[param] : null;
    }

})();​

Ze względu na nowe API historii HTML, a konkretnie history.pushState() i history.replaceState(), adres URL może ulec zmianie, Co unieważni pamięć podręczną parametrów i ich wartości.

Ta wersja będzie aktualizować swoją wewnętrzną pamięć podręczną parametrów za każdym razem, gdy zmieni się historia.

 166
Author: alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-09 16:13:29

Wystarczy użyć dwóch splitów:

function get(n) {
    var half = location.search.split(n + '=')[1];
    return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}
Czytałam wszystkie poprzednie i pełniejsze odpowiedzi. Ale myślę, że jest to najprostsza i szybsza metoda. Możesz sprawdzić w tym jsperf benchmark

Aby rozwiązać problem w komentarzu Rup, dodaj podział warunkowy, zmieniając pierwszą linię na dwie poniżej. Ale absolutna dokładność oznacza, że jest teraz wolniejsza niż wyrażenie regularne (zobacz jsPerf ).

function get(n) {
    var half = location.search.split('&' + n + '=')[1];
    if (!half) half = location.search.split('?' + n + '=')[1];
    return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}
Więc jeśli wiesz, że nie wpadniesz na kontrkandydat Rupa, to wygra. W przeciwnym razie regexp.

lub jeśli masz kontrolę nad querystring i możesz zagwarantować, że wartość, którą próbujesz uzyskać, nigdy nie będzie zawierać zakodowanego adresu URL znaków (posiadanie ich w wartości byłoby złym pomysłem) - można użyć następująca nieco bardziej uproszczona i czytelna Wersja 1. opcji:

    function getQueryStringValueByName(name) {
        var queryStringFromStartOfValue = location.search.split(name + '=')[1];
         return queryStringFromStartOfValue !== undefined ? queryStringFromStartOfValue.split('&')[0] : null;
 102
Author: Martin Borthiry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-26 03:58:31

Oto moja próba stworzenia doskonałego rozwiązania Andy ' ego E w pełnowartościową wtyczkę jQuery:

;(function ($) {
    $.extend({      
        getQueryString: function (name) {           
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams(); 

            return this.queryStringParams[name];
        }
    });
})(jQuery);

Składnia jest następująca:

var someVar = $.getQueryString('myParam');

Najlepsze z obu światów!

 96
Author: Ryan Phelan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-05 20:49:37

Jeśli robisz więcej manipulacji URL niż po prostu parsowanie querystring, możesz znaleźć URI.js pomocny. Jest to biblioteka do manipulowania adresami URL - i jest dostarczana ze wszystkimi dzwonkami i gwizdkami. (Sorry za self-advertising tutaj)

Aby przekonwertować zapytanie na mapę:

var data = URI('?foo=bar&bar=baz&foo=world').query(true);
data == {
  "foo": ["bar", "world"],
  "bar": "baz"
}

(URI.js również "naprawia" złe zapytania jak ?&foo&&bar=baz& do ?foo&bar=baz)

 76
Author: rodneyrehm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-20 14:18:01

Podoba mi się rozwiązanie Ryana Phelana. Ale nie widzę sensu rozszerzania jQuery w tym celu? Nie ma zastosowania funkcjonalność jQuery.

Z drugiej strony podoba mi się wbudowana funkcja w Google Chrome: window.miejsce.getParameter.

Dlaczego więc tego nie użyć? Ok, inne przeglądarki nie mają. Więc stwórzmy tę funkcję, jeśli ona nie istnieje:
if (!window.location.getParameter ) {
  window.location.getParameter = function(key) {
    function parseParams() {
        var params = {},
            e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q = window.location.search.substring(1);

        while (e = r.exec(q))
            params[d(e[1])] = d(e[2]);

        return params;
    }

    if (!this.queryStringParams)
        this.queryStringParams = parseParams(); 

    return this.queryStringParams[key];
  };
}

Ta funkcja jest mniej więcej od Ryana Phelana, ale jest zawinięta inaczej: clear name I no zależności innych bibliotek javascript. więcej o tej funkcji na moim blogu .

 64
Author: Anatoly Mironov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-10 18:44:59

Keep it simple in plain JavaScript code:

function qs(key) {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars[key];
}

Wywołaj go z dowolnego miejsca w kodzie JavaScript:

var result = qs('someKey');
 57
Author: sagivo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-24 14:22:07

Oto szybki sposób na uzyskanie obiektu podobnego do tablicy PHP $_GET :

function get_query(){
    var url = location.search;
    var qs = url.substring(url.indexOf('?') + 1).split('&');
    for(var i = 0, result = {}; i < qs.length; i++){
        qs[i] = qs[i].split('=');
        result[qs[i][0]] = decodeURIComponent(qs[i][1]);
    }
    return result;
}

Użycie:

var $_GET = get_query();

Dla ciągu zapytania x=5&y&z=hello&x=6 zwraca obiekt:

{
  x: "6",
  y: undefined,
  z: "hello"
}
 54
Author: Paulpro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-09 12:00:26

To są świetne odpowiedzi, ale potrzebowałem czegoś bardziej solidnego i pomyślałem, że wszyscy chcielibyście mieć to, co stworzyłem.

Jest to prosta metoda biblioteczna, która zajmuje się sekcją i manipulacją parametrami URL. Metoda statyczna posiada następujące pod metody, które można wywołać w temacie URL:

  • getHost
  • getPath
  • getHash
  • setHash
  • getParams
  • getQuery
  • setParam
  • getParam
  • hasParam
  • removeParam

Przykład:

URLParser(url).getParam('myparam1')

var url = "http://www.test.com/folder/mypage.html?myparam1=1&myparam2=2#something";

function URLParser(u){
    var path="",query="",hash="",params;
    if(u.indexOf("#") > 0){
        hash = u.substr(u.indexOf("#") + 1);
        u = u.substr(0 , u.indexOf("#"));
    }
    if(u.indexOf("?") > 0){
        path = u.substr(0 , u.indexOf("?"));
        query = u.substr(u.indexOf("?") + 1);
        params= query.split('&');
    }else
        path = u;
    return {
        getHost: function(){
            var hostexp = /\/\/([\w.-]*)/;
            var match = hostexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getPath: function(){
            var pathexp = /\/\/[\w.-]*(?:\/([^?]*))/;
            var match = pathexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getHash: function(){
            return hash;
        },
        getParams: function(){
            return params
        },
        getQuery: function(){
            return query;
        },
        setHash: function(value){
            if(query.length > 0)
                query = "?" + query;
            if(value.length > 0)
                query = query + "#" + value;
            return path + query;
        },
        setParam: function(name, value){
            if(!params){
                params= new Array();
            }
            params.push(name + '=' + value);
            for (var i = 0; i < params.length; i++) {
                if(query.length > 0)
                    query += "&";
                query += params[i];
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
        getParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return decodeURIComponent(pair[1]);
                }
            }
            console.log('Query variable %s not found', name);
        },
        hasParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return true;
                }
            }
            console.log('Query variable %s not found', name);
        },
        removeParam: function(name){
            query = "";
            if(params){
                var newparams = new Array();
                for (var i = 0;i < params.length;i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) != name)
                          newparams .push(params[i]);
                }
                params = newparams;
                for (var i = 0; i < params.length; i++) {
                    if(query.length > 0)
                        query += "&";
                    query += params[i];
                }
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
    }
}


document.write("Host: " + URLParser(url).getHost() + '<br>');
document.write("Path: " + URLParser(url).getPath() + '<br>');
document.write("Query: " + URLParser(url).getQuery() + '<br>');
document.write("Hash: " + URLParser(url).getHash() + '<br>');
document.write("Params Array: " + URLParser(url).getParams() + '<br>');
document.write("Param: " + URLParser(url).getParam('myparam1') + '<br>');
document.write("Has Param: " + URLParser(url).hasParam('myparam1') + '<br>');

document.write(url + '<br>');

// Remove the first parameter
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove the first parameter<br>');

// Add a third parameter
url = URLParser(url).setParam('myparam3',3);
document.write(url + ' - Add a third parameter<br>');

// Remove the second parameter
url = URLParser(url).removeParam('myparam2');
document.write(url + ' - Remove the second parameter<br>');

// Add a hash
url = URLParser(url).setHash('newhash');
document.write(url + ' - Set Hash<br>');

// Remove the last parameter
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove the last parameter<br>');

// Remove a parameter that doesn't exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a parameter that doesn\"t exist<br>');
 46
Author: meagar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-24 13:58:05

Z MDN :

function loadPageVar (sVar) {
  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

alert(loadPageVar("name"));
 45
Author: orip,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-09 11:36:23

Kod:

var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
    var s = a[i].split("=");
    a[i]  = a[unescape(s[0])] = unescape(s[1]);
}

Pokaż to!

for (i in a) {
    document.write(i + ":" + a[i] + "<br/>");   
};

Na moim Macu: test.htm?i=can&has=cheezburger wyświetla

0:can
1:cheezburger
i:can
has:cheezburger
 40
Author: shanimal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-30 15:36:48

Często używam wyrażeń regularnych, ale nie do tego.

Wydaje mi się łatwiejsze i bardziej efektywne odczytanie ciągu zapytania raz w mojej aplikacji i zbudowanie obiektu ze wszystkich par klucz / wartość, takich jak:

var search = function() {
  var s = window.location.search.substr(1),
    p = s.split(/\&/), l = p.length, kv, r = {};
  if (l === 0) {return false;}
  while (l--) {
    kv = p[l].split(/\=/);
    r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
  }
  return r;
}();

Dla adresów URL takich jak http://domain.com?param1=val1&param2=val2 możesz uzyskać ich wartość później w kodzie jako search.param1 i search.param2.

 40
Author: Mic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-24 14:17:23
function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 3
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3
 38
Author: Jet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 13:03:19

Metoda Roshambo jQuery nie dbała o dekodowanie URL

Http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

Dodałem tę możliwość również podczas dodawania w instrukcji return

return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;

Teraz możesz znaleźć zaktualizowany gist:

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
 38
Author: Mohammed Arif,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 06:00:35

Oto moja edycja ta doskonała odpowiedź - z dodaną możliwością parsowania łańcuchów zapytań z kluczami bez wartości.

var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i) {
        var p=a[i].split('=', 2);
        if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
        b[p[0]] = p[1];
    }
    return b;
})((url.split('?'))[1].split('&'));

Ważne! parametr dla tej funkcji w ostatnim wierszu jest inny. To tylko przykład, jak można przekazać dowolny adres URL do niego. Możesz użyć ostatniego wiersza z odpowiedzi Bruno, aby przeanalizować bieżący adres URL.

Więc co dokładnie się zmieniło? Z adresem url http://sb.com/reg/step1?param= wyniki będą takie same. Ale z url http://sb.com/reg/step1?param Rozwiązanie Bruno zwraca obiekt bez keys, podczas gdy mine zwraca obiekt o wartości key param i undefined.
 37
Author: skaurus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:37

I like this one (taken from jquery-howto.blogspot.co.uk): {]}

// get an array with all querystring values
// example: var valor = getUrlVars()["valor"];
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
Dla mnie działa świetnie.
 36
Author: Tomamais,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-09 18:14:12

Potrzebowałem obiektu z łańcucha zapytania i nienawidzę wielu kodów. Może nie jest najbardziej wytrzymały we wszechświecie, ale to tylko kilka linijek kodu.

var q = {};
location.href.split('?')[1].split('&').forEach(function(i){
    q[i.split('=')[0]]=i.split('=')[1];
});

URL taki jak this.htm?hello=world&foo=bar utworzy:

{hello:'world', foo:'bar'}
 34
Author: tim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-24 14:01:09

Oto rozszerzona wersja linked Andy E 'S"Handle array-style query strings" -version. Naprawiono błąd (?key=1&key[]=2&key[]=3; 1 został utracony i zastąpiony przez [2,3]), dokonał kilku drobnych ulepszeń wydajności(ponowne dekodowanie wartości, przeliczanie pozycji " [", itp.) i dodano szereg ulepszeń (funkcjonalizowana, obsługa ograniczników ?key=1&key=2, obsługa ograniczników ;). Pozostawiłem zmienne irytująco krótkie, ale dodałem komentarze, aby były czytelne (oh, i ponownie użyłem v w lokalnych funkcjach, przepraszam, jeśli to jest mylące ;).

Będzie obsługiwał następujące querystring...

?test=Hello&person=neek&person[]=jeff&person []=jim&person[extra]=john&test3&nocache = 1398914891264

...robiąc z niego obiekt, który wygląda...

{
    "test": "Hello",
    "person": {
        "0": "neek",
        "1": "jeff",
        "2": "jim",
        "length": 3,
        "extra": "john"
    },
    "test3": "",
    "nocache": "1398914891264"
}

Jak widać powyżej, ta wersja obsługuje pewną miarę "zniekształconych" tablic, np. - person=neek&person[]=jeff&person[]=jim lub {[9] } ponieważ klucz jest identyfikowalny i ważny (przynajmniej w dotNet NameValueCollection.Dodaj):

Jeśli podany klucz już istnieje w nazwie docelowejvaluecollection przykład, określona wartość jest dodawana do istniejącego oddzielonego przecinkami lista wartości w formie "value1, value2, value3".

Wydaje się jury jest nieco out na powtarzających się klawiszy, ponieważ nie ma spec. W tym przypadku wiele kluczy jest przechowywanych jako (fałszywa)tablica. Ale należy pamiętać, że I nie przetwarza wartości oparte na przecinkach na tablice.

Kod:

getQueryStringKey = function(key) {
    return getQueryStringAsObject()[key];
};


getQueryStringAsObject = function() {
    var b, cv, e, k, ma, sk, v, r = {},
        d = function (v) { return decodeURIComponent(v).replace(/\+/g, " "); }, //# d(ecode) the v(alue)
        q = window.location.search.substring(1), //# suggested: q = decodeURIComponent(window.location.search.substring(1)),
        s = /([^&;=]+)=?([^&;]*)/g //# original regex that does not allow for ; as a delimiter:   /([^&=]+)=?([^&]*)/g
    ;

    //# ma(make array) out of the v(alue)
    ma = function(v) {
        //# If the passed v(alue) hasn't been setup as an object
        if (typeof v != "object") {
            //# Grab the cv(current value) then setup the v(alue) as an object
            cv = v;
            v = {};
            v.length = 0;

            //# If there was a cv(current value), .push it into the new v(alue)'s array
            //#     NOTE: This may or may not be 100% logical to do... but it's better than loosing the original value
            if (cv) { Array.prototype.push.call(v, cv); }
        }
        return v;
    };

    //# While we still have key-value e(ntries) from the q(uerystring) via the s(earch regex)...
    while (e = s.exec(q)) { //# while((e = s.exec(q)) !== null) {
        //# Collect the open b(racket) location (if any) then set the d(ecoded) v(alue) from the above split key-value e(ntry) 
        b = e[1].indexOf("[");
        v = d(e[2]);

        //# As long as this is NOT a hash[]-style key-value e(ntry)
        if (b < 0) { //# b == "-1"
            //# d(ecode) the simple k(ey)
            k = d(e[1]);

            //# If the k(ey) already exists
            if (r[k]) {
                //# ma(make array) out of the k(ey) then .push the v(alue) into the k(ey)'s array in the r(eturn value)
                r[k] = ma(r[k]);
                Array.prototype.push.call(r[k], v);
            }
            //# Else this is a new k(ey), so just add the k(ey)/v(alue) into the r(eturn value)
            else {
                r[k] = v;
            }
        }
        //# Else we've got ourselves a hash[]-style key-value e(ntry) 
        else {
            //# Collect the d(ecoded) k(ey) and the d(ecoded) sk(sub-key) based on the b(racket) locations
            k = d(e[1].slice(0, b));
            sk = d(e[1].slice(b + 1, e[1].indexOf("]", b)));

            //# ma(make array) out of the k(ey) 
            r[k] = ma(r[k]);

            //# If we have a sk(sub-key), plug the v(alue) into it
            if (sk) { r[k][sk] = v; }
            //# Else .push the v(alue) into the k(ey)'s array
            else { Array.prototype.push.call(r[k], v); }
        }
    }

    //# Return the r(eturn value)
    return r;
};
 34
Author: Campbeln,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-27 13:37:45

To funkcja, którą stworzyłem jakiś czas temu i jestem z niej całkiem zadowolony. Nie rozróżnia wielkości liter - co jest przydatne. Ponadto, jeśli żądany QS nie istnieje, po prostu zwraca pusty łańcuch.

Używam skompresowanej wersji tego. Umieszczam nieskompresowane dla początkujących typów, aby lepiej wyjaśnić, co się dzieje.

Jestem pewien, że można to zoptymalizować lub zrobić inaczej, aby działać szybciej, ale zawsze działało świetnie dla tego, czego potrzebuję.

Smacznego.
function getQSP(sName, sURL) {
    var theItmToRtn = "";
    var theSrchStrg = location.search;
    if (sURL) theSrchStrg = sURL;
    var sOrig = theSrchStrg;
    theSrchStrg = theSrchStrg.toUpperCase();
    sName = sName.toUpperCase();
    theSrchStrg = theSrchStrg.replace("?", "&") theSrchStrg = theSrchStrg + "&";
    var theSrchToken = "&" + sName + "=";
    if (theSrchStrg.indexOf(theSrchToken) != -1) {
        var theSrchTokenLth = theSrchToken.length;
        var theSrchTokenLocStart = theSrchStrg.indexOf(theSrchToken) + theSrchTokenLth;
        var theLocOfNextAndSign = theSrchStrg.indexOf("&", theSrchTokenLocStart);
        theItmToRtn = unescape(sOrig.substring(theSrchTokenLocStart, theLocOfNextAndSign));
    }
    return unescape(theItmToRtn);
}
 31
Author: Clint,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-04 09:00:25

Właśnie wypuściliśmy arg.JS, projekt mający na celu rozwiązanie tego problemu raz na zawsze. Tradycyjnie było tak ciężko, ale teraz Można:

var name = Arg.get("name");

Lub uzyskanie całej partii:

var params = Arg.all();

A jeśli zależy ci na różnicy między ?query=true i #hash=true, możesz użyć metod Arg.query() i Arg.hash().

 27
Author: Mat Ryer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-30 17:37:08

Problem z najlepszą odpowiedzią na to pytanie polega na tym, że nie są obsługiwane parametry umieszczone po#, ale czasami jest to potrzebne, aby uzyskać tę wartość również.

Zmodyfikowałem odpowiedź, aby mogła analizować pełny ciąg zapytania ze znakiem hash również:

var getQueryStringData = function(name) {
    var result = null;
    var regexS = "[\\?&#]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec('?' + window.location.href.split('?')[1]);
    if (results != null) {
        result = decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    return result;
};
 27
Author: Ph0en1x,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-24 14:04:08

Jeśli używasz Browserify, możesz użyć modułu urlz węzła .js :

var url = require('url');

url.parse('http://example.com/?bob=123', true).query;

// returns { "bob": "123" }

Czytaj dalej: węzeł URL.js v0.12.2 Podręcznik i dokumentacja

EDIT: możesz użyć URL Interfejs, jest dość szeroko przyjęty w prawie wszystkich nowych przeglądarkach i jeśli kod ma działać na starej przeglądarce, możesz użyć polyfill jak ten . Oto przykład kodu, jak używać interfejsu URL, aby uzyskać parametry zapytania (aka search parametry)

const url = new URL('http://example.com/?bob=123');
url.searchParams.get('bob'); 

Możesz również użyć do tego URLSearchParams, oto przykład z MDN aby to zrobić z URLSearchParams:

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {
  console.log(p);
}

searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
 27
Author: nkh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-01 20:41:58
function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');

    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

I tak możesz użyć tej funkcji zakładając, że adres URL to

http://dummy.com/?stringtext=jquery&stringword=jquerybyexample

var tech = GetQueryStringParams('stringtext');
var blog = GetQueryStringParams('stringword');
 25
Author: gewel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-16 07:56:34