Get the values from the "GET" parameters (JavaScript) [duplicate]
Asked Answered
H

63

1735

I have a URL with some GET parameters as follows:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using JavaScript?

Humectant answered 11/6, 2009 at 8:32 Comment(1)
Before you post a new answer, consider there are already 50+ answers for this question. Please, make sure that your answer contributes information that is not among existing answers.Durward
V
2682

JavaScript itself has nothing built in for handling query string parameters.

Code running in a (modern) browser can use the URL object (a Web API). URL is also implemented by Node.js:

// You can get url_string from window.location.href if you want to work with
// the URL of the current page
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; 
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

For older browsers (including Internet Explorer), you can use this polyfill.

You could also use one for URLSearchParams and extract the query string to pass to it with window.location.search.substring(1).


You could also use the code from the original version of this answer that predates URL. The above polyfill is robust and well tested and I strongly recommend it over this though.

You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.

Then you can parse it with this:

function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair.shift());
    var value = decodeURIComponent(pair.join("="));
    // If first entry with this name
    if (typeof query_string[key] === "undefined") {
      query_string[key] = value;
      // If second entry with this name
    } else if (typeof query_string[key] === "string") {
      var arr = [query_string[key], value];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(value);
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);

You can get the query string from the URL of the current page with:

var query = window.location.search.substring(1);
var qs = parse_query_string(query);
Vallievalliere answered 11/6, 2009 at 8:37 Comment(2)
For older browsers, you may need a polyfill for URL in addition to the one for URLSearchParams. Or you can dodge this issue by replacing the line var c = url.searchParams.get("c"); in the answer above with var c = new URLSearchParams(window.location.search).get("c");.Scoggins
Wow, this is extremely useful even in front-end exclusive pages: You could just share a link with parameters and use this code to preload some variables to generate a certain shared view.Ferocious
I
269

Most implementations I've seen miss out URL-decoding the names and the values.

Here's a general utility function that also does proper URL-decoding:

function getQueryParams(qs) {
    qs = qs.split('+').join(' ');

    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

//var query = getQueryParams(document.location.search);
//alert(query.foo);
Inhabited answered 8/7, 2009 at 18:4 Comment(12)
This code doesn't work. It creates an infinite loop because the regex is compiled in the loop definition which resets the current index. It works properly if you put the regex into a variable outside of the loop.Litho
@maxhawkins: It works in some browsers while it would go into an infinite loop in others. You're half-right in that regard. I will fix the code to be cross-browser. Thanks for pointing that out!Inhabited
re = /(\?|\&)([^=]+)=([^&]*)/g; and tokens 2 and 3Heterodox
if i use yours i get the first param with URL, example: example.html?a=b&c=d i get example.html?a -> b, c -> dHeterodox
@Heterodox This function is to be used with the query part of a URL, not the entire URL. See the commented-out usage example below.Inhabited
Jslint does not like the "insecure" ^ in the regex.Missioner
This works okay but it returns case sensitive params which through me off.Mantinea
@Harvey Case insensitivity is not a concern of query parameters. It sounds like an application-specific thing that should be applied along with, or on top of query parameter extraction.Inhabited
This also works with base64 tokens which might contain an = char.Narcolepsy
Why qs.split('+').join(' '); and not qs.replace(/\+/g, ' '); ?Eunuchoidism
qs.split('+').join(' '); is not necessary, because whitespace code is %20 and it's decoded by decodeURIComponentNa
Much better answer than acceptedAutum
W
261

source

function gup( name, url ) {
    if (!url) url = location.href;
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')
Windstorm answered 11/6, 2009 at 8:38 Comment(7)
I like this option best, but prefer to return null, or the result, but not an empty string.Prothonotary
It looks like you have some extra escape chars. "\\[" should be "\[". Since those are regular strings, the [ and ] don't need to be escaped.Alphonsealphonsine
This is not case insensitive. Where would I add the "i" to make it case insensitive?Colobus
alert(gup('UserID', window.location.href));Araujo
if there is no parameters in the URL, results will be Null and generate an error. testing for null before attempting to parse the array could be betterJowers
use decodeURIComponent() on results[1] to handle encoded parameter valuesPeriwinkle
gup = getUrlParameter :)Ticon
P
250

This is an easy way to check just one parameter:

Example URL:

http://myserver/action?myParam=2

Example Javascript:

var myParam = location.search.split('myParam=')[1]

if "myParam" exists in the URL... variable myParam will contain "2", otherwise it will be undefined.

Maybe you want a default value, in that case:

var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';

Update: This works better:

var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';

And it works right even when URL is full of parameters.

Price answered 2/12, 2013 at 19:19 Comment(6)
This only works if the parameter you're grabbing is the last one in the URL, which you shouldn't depend on (even if you're only expecting one parameter). e.g. http://myserver/action?myParam=2&anotherParam=3 would yield not "2" but "2&anotherParam=3".Oscillation
(location.search.split('myParam=')[1]||'').split('&')[0] -- to use with multiple params or possibliy missing myParam.Loyalist
or location.search.split('myParam=').splice(1).join('').split('&')[0]Milky
You can gain more precision and allow any order of parameters by prepending with [?|&] as in [?|&]myParam=([^&]+)Completion
You may need to decode the value result = decodeURIComponent(result);Completion
When I tried this code it's working but my PC freezing after a while.Telium
R
160

Browsers vendors have implemented a native way to do this via URL and URLSearchParams.

let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c'));  // outputs "m2-m3-m4-m5"

Currently supported in Firefox, Opera, Safari, Chrome and Edge. For a list of browser support see here.

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

https://url.spec.whatwg.org/

Eric Bidelman, an engineer at Google, recommends using this polyfill for unsupported browsers.

Ride answered 18/2, 2016 at 17:52 Comment(13)
According to the MDN link(s) Safari support URL but not URLSearchParams.Mezzorelievo
@Markouver Isn't the polyfill take care of that? BTW, Safari is the modern days' IE6Cauley
Why is new URLSearchParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5").get('a') returning null for me? (On Chrome stable). b and c seem to work well.Woodworth
Updated answer. My original answer was not properly using URLSearchParams, as it's only designed to work with the querystring portion of the URL.Ride
What version? Latest?Ride
Use url.searchParams instead new URLSearchParams(url.search).Dissonancy
@CaioTarifa that property doesnt exist on the windowRide
Safari has support for it nowStannum
@JochenBedersdorfer Edge was just added too! Updated post.Ride
it fails if I add # at the endCormick
In addition to this, if you are needing to replace any of these params with new values, calling url.searchparams.set(param, newValue) with replace the selected existing parameter with the provided newValue.Asomatous
This is ideal since it decodes URI encoded string values for you. awesomeChophouse
it doesn't seems to return the first param value.Philosopher
H
107

I found this ages ago, very easy:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

Then call it like this:

var fType = getUrlVars()["type"];
Hawsepiece answered 20/11, 2013 at 14:1 Comment(5)
Very nice, it also works using location.search instead of window.location.hrefVelarium
@pdxbmw It is useless and should be removed. The code may seem clever at first glance, but isn't very well thought out. Improvements: Use decodeURIComponent() on value, because that's what you usually want to work with; use window.location.search instead of window.location.href, because you are only interested in the parameters, not the whole url.Dreiser
I used it in my es6 project: decodeURIComponent(window.location.search).replace(/[?&]+([^=&]+)=([^&]*)/g, (m, key, value) => params[key] = value);Ebba
@Dreiser suggestion worked great. I was getting in an ID 142# because at the end of the URL was the # generated on a button click. Leaving the function like this var vars = {}; window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;Gianna
var parts isn't necessaryNeumark
F
83

You can get the query string in location.search, then you can split everything after the question mark:

var params = {};

if (location.search) {
    var parts = location.search.substring(1).split('&');

    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}

// Now you can get the parameters you want like so:
var abc = params.abc;
Flypaper answered 11/6, 2009 at 8:37 Comment(3)
What about URL-decoding the parameter names and values?Inhabited
This approach doesn't handle arrays. E.g. ?array[]=1&array[]=2 produces {"array[]": "2"}, which is clearly wrong.Carlettacarley
@Carlettacarley There is no clear right or wrong here. First of all, repeated fields with the same names have no specified standard behavior, and is up to the parser to handle. Additionally, the [] pattern only has a meaning in some cases (e.g., PHP), but not others. So not "clearly wrong" – just not implemented to handle a non-standard case that you may or may not need to handle.Flypaper
A
54

A super simple way using URLSearchParams.

function getParam(param){
  return new URLSearchParams(window.location.search).get(param);
}

It's currently supported in Chrome, Firefox, Safari, Edge, and others.

Argueta answered 12/4, 2017 at 20:16 Comment(4)
Get the error: 'SCRIPT5009: 'URLSearchParams' is not defined' when running in Edge.Demonetize
@AndreasPresthammer What version of edge?Argueta
@spencer-sm Microsoft Edge 41.16299.820.0Demonetize
@iiiml0sto1 What are "prettified URL parameters" ?Argueta
R
39

I wrote a more simple and elegant solution.

var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];
Ranunculus answered 14/10, 2014 at 23:3 Comment(7)
Look at that, two lines, does exactly what it says on the tin - and won't break if someone is trying to probe for vulnerabilities and adds a bunch of extra characters and queries unlike a couple of these solutions. Cheers chap!Cither
This does the job right and only in 2 lines. Great answer!Gianna
I think it would be handy for other a check for null was included. If not, an example is here: https://mcmap.net/q/45105/-get-the-values-from-the-quot-get-quot-parameters-javascript-duplicate (I had an edit attempt rejected).Watchman
Don't understand... how does this answer the question, which is about getting params from a specific string, 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5'?Bobbe
Loved this answer, +1'ed. Just a suggestion, you can replace [0-9] for \dProteolysis
Clever, but what does it say "on the tin", exactly? Looks to me like it only works if the parameter contains numeric digits, and it can't handle the OP's question, where the parameter is m2-m3-m4-m5??Granese
it also matches noroom=1234, not desirableMundell
S
34

Here is a recursive solution that has no regex, and has minimal mutation (only the params object is mutated, which I believe is unavoidable in JS).

It's awesome because it:

  • Is recursive
  • Handles multiple parameters of the same name
  • Deals well with malformed parameter strings (missing values, so on)
  • Doesn't break if '=' is in the value
  • Performs URL decoding
  • And lastly, It's awesome because it...argh!!!

Code:

var get_params = function(search_string) {

  var parse = function(params, pairs) {
    var pair = pairs[0];
    var parts = pair.split('=');
    var key = decodeURIComponent(parts[0]);
    var value = decodeURIComponent(parts.slice(1).join('='));

    // Handle multiple parameters of the same name
    if (typeof params[key] === "undefined") {
      params[key] = value;
    } else {
      params[key] = [].concat(params[key], value);
    }

    return pairs.length == 1 ? params : parse(params, pairs.slice(1))
  }

  // Get rid of leading ?
  return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}

var params = get_params(location.search);

// Finally, to get the param you want
params['c'];
Suspensor answered 16/1, 2014 at 1:42 Comment(5)
You... you said recursive twice.Pisciform
It can't find the first param in the next url : www.mysite.com?first=1&second=2Wenda
Hi Mario, here is a JSFiddle showing it working with that URL: jsfiddle.net/q6xfJ - If you have found an error, is this perhaps browser specific? When testing, please note that the answer I supplied uses location.search, which is the '?first=1&second=2' part of the URL. Cheers :)Suspensor
I don't see why something is good just because it is recursive.Elielia
Erm, I think you missed the recursion joke there Adam. Although now everyone will miss it because edi9999 removed the second "Is recursive".Suspensor
F
32

I made a function that does this:

var getUrlParams = function (url) {
  var params = {};
  (url + '?').split('?')[1].split('&').forEach(function (pair) {
    pair = (pair + '=').split('=').map(decodeURIComponent);
    if (pair[0].length) {
      params[pair[0]] = pair[1];
    }
  });
  return params;
};

Update 5/26/2017, here is an ES7 implementation (runs with babel preset stage 0, 1, 2, or 3):

const getUrlParams = url => `${url}?`.split('?')[1]
  .split('&').reduce((params, pair) =>
    ((key, val) => key ? {...params, [key]: val} : params)
    (...`${pair}=`.split('=').map(decodeURIComponent)), {});

Some tests:

console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}

Update 3/26/2018, here is a Typescript implementation:

const getUrlParams = (search: string) => `${search}?`
  .split('?')[1]
  .split('&')
  .reduce(
    (params: object, pair: string) => {
      const [key, value] = `${pair}=`
        .split('=')
        .map(decodeURIComponent)

      return key.length > 0 ? { ...params, [key]: value } : params
    },
    {}
  )

Update 2/13/2019, here is an updated TypeScript implementation that works with TypeScript 3.

interface IParams { [key: string]: string }

const paramReducer = (params: IParams, pair: string): IParams => {
  const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)

  return key.length > 0 ? { ...params, [key]: value } : params
}

const getUrlParams = (search: string): IParams =>
  `${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})
Fr answered 25/6, 2015 at 17:45 Comment(4)
On a URL without query parameters this will return Object {"": ""}Bohman
Looks clean enough to me. The rest of the answers are just too much "magic" without enough explanation.Yuriyuria
This is an awesome answer!Bascomb
Thanks @SpencerBigum !Fr
E
26

See this

function getURLParameters(paramName)
{
    var sURL = window.document.URL.toString();
    if (sURL.indexOf("?") > 0)
    {
        var arrParams = sURL.split("?");
        var arrURLParams = arrParams[1].split("&");
        var arrParamNames = new Array(arrURLParams.length);
        var arrParamValues = new Array(arrURLParams.length);

        var i = 0;
        for (i = 0; i<arrURLParams.length; i++)
        {
            var sParam =  arrURLParams[i].split("=");
            arrParamNames[i] = sParam[0];
            if (sParam[1] != "")
                arrParamValues[i] = unescape(sParam[1]);
            else
                arrParamValues[i] = "No Value";
        }

        for (i=0; i<arrURLParams.length; i++)
        {
            if (arrParamNames[i] == paramName)
            {
                //alert("Parameter:" + arrParamValues[i]);
                return arrParamValues[i];
            }
        }
        return "No Parameters Found";
    }
}
Ephesians answered 5/1, 2012 at 20:18 Comment(0)
B
25

The shortest way:

new URL(location.href).searchParams.get("my_key");
Benedix answered 11/8, 2018 at 15:9 Comment(2)
I would favor using new URL(location.href).searchParams.get("my_key") over URLSearchParams since the latter will fail when retrieving the first query parameter of any URL.Candra
Tested both variants. I agree with you. Edited the answer.Benedix
C
20

ECMAScript 6 solution:

var params = window.location.search
  .substring(1)
  .split("&")
  .map(v => v.split("="))
  .reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())
Campanulaceous answered 23/6, 2015 at 13:10 Comment(2)
Nice. FYI, because it's a Map, usage is params.get("key");Efferent
I like it but probably it won't get the first param. I created a function based on your example function urlParams(url) { const [, searchParams = ''] = url.split('?') return searchParams.split('&') .map(v => v.split('=')) .reduce((map, [key = '', value]) => key.length ? map.set(key, decodeURIComponent(value)) : map, new Map()) }Assure
U
15

I use the parseUri library. It allows you to do exactly what you are asking for:

var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'
Uriisa answered 14/8, 2011 at 22:25 Comment(0)
G
12

I use

function getVal(str) {
    var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
    return v ? v[1] : null;
}
Geocentric answered 18/3, 2016 at 5:31 Comment(4)
Please add some explanation. Your answer is currently flagged "low quality" and might eventually be removed without.Calque
I found that if there has a string like '#id' at the end of the url,and return the last parameter value like 'somevalue#id'Speaker
@Speaker window.location.search won't include hash like #id.Geocentric
@Geocentric Yes,you are right,i made a mistake that use location.hrefto match the result instead of the location.search.Thank you.Speaker
K
11

Here is my solution. As advised by Andy E while answering this question, it's not good for your script's performance if it's repeatedly building various regex strings, running loops etc just to get a single value. So, I've come up with a simpler script that returns all the GET parameters in a single object. You should call it just once, assign the result to a variable and then, at any point in the future, get any value you want from that variable using the appropriate key. Note that it also takes care of URI decoding (i.e things like %20) and replaces + with a space:

 function getUrlQueryParams(url) {
  var queryString = url.split("?")[1];
  var keyValuePairs = queryString.split("&");
  var keyValue = [];
  var queryParams = {};
  keyValuePairs.forEach(function(pair) {
    keyValue = pair.split("=");
    queryParams[keyValue[0]] = decodeURIComponent(keyValue[1]).replace(/\+/g, " ");
});
  return queryParams;
}

So, here are are a few tests of the script for you to see:

// Query parameters with strings only, no special characters.
var currentParams = getUrlQueryParams("example.com/foo?number=zero");
alert(currentParams["number"]); // Gives "zero".

// For the URL you stated above...
var someParams = getUrlQueryParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ");
alert(someParams["c"]); // Gives "m2-m3-m4-m5".

// For a query params with URI encoding...
var someParams = getUrlQueryParams("www.example.com/t.html?phrase=a%20long%20shot&location=Silicon+Valley%2C+USA");
alert(someParams["phrase"]); // Gives "a long shot".
alert(someParams["location"]); // Gives "Silicon Valley, USA".
Kurtz answered 21/9, 2016 at 22:10 Comment(1)
.replace("+", " ") will only replace the first occurrence You need to use .replace(/\+/g, " ");Stagemanage
H
10

this question has too many answers, so i'm adding another one.

/**
 * parses and returns URI query parameters 
 * 
 * @param {string} param parm
 * @param {bool?} asArray if true, returns an array instead of a scalar 
 * @returns {Object|Array} 
 */
function getURIParameter(param, asArray) {
    return document.location.search.substring(1).split('&').reduce(function(p,c) {
        var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
        if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
        return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
    }, []);
}

usage:

getURIParameter("id")  // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids

this copes with empty parameters (those keys present without "=value"), exposure of both a scalar and array-based value retrieval API, as well as proper URI component decoding.

Hairdo answered 28/4, 2014 at 3:27 Comment(0)
T
10

The easiest way using the replace() method:

From the urlStr string:

paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');

or from the current URL:

paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');

Explanation:

  • document.URL - interface returns the document location (page url) as a string.
  • replace() - method returns a new string with some or all matches of a pattern replaced by a replacement.
  • /.*param_name=([^&]*).*/ - the regular expression pattern enclosed between slashes which means:
    • .* - zero or more of any characters,
    • param_name= - param name which is serched,
    • () - group in regular expression,
    • [^&]* - one or more of any characters excluding &,
    • | - alternation,
    • $1 - reference to first group in regular expression.

var urlStr = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';
var c = urlStr.replace(/.*c=([^&]*).*|(.*)/, '$1');
var notExisted = urlStr.replace(/.*not_existed=([^&]*).*|(.*)/, '$1');
console.log(`c === '${c}'`);
console.log(`notExisted === '${notExisted}'`);
Terrie answered 23/7, 2019 at 14:48 Comment(2)
Nice solution, but if the parameter is not found, the whole string is returned. I would expect "undefined" in this case.Mccaffrey
Hi @pensan, thank you for your great comment. I just add to the regular expression the handling of the situation when the parameter does not appear in the URL. In this case we get the emty string (not whole string).Terrie
P
8

Yet another suggestion.

There are some good answers already, but I found them needlessly complex and hard to understand. This is short, simple, and returns a simple associative array with key names corresponding to the token names in the URL.

I added a version with comments below for those who want to learn.

Note this relies on jQuery ($.each) for its loop, which I recommend instead of forEach. I find it simpler to ensure cross-browser compatibility using jQuery across the board rather than plugging in individual fixes to support whichever new functions aren't supported in older browsers.

Edit: After I wrote this I noticed Eric Elliott's answer, which is almost the same, though it uses forEach, while I'm generally against (for reasons stated above).

function getTokens(){
    var tokens = [];
    var query = location.search;
    query = query.slice(1);
    query = query.split('&');
    $.each(query, function(i,value){    
        var token = value.split('=');   
        var key = decodeURIComponent(token[0]);     
        var data = decodeURIComponent(token[1]);
        tokens[key] = data;
    });
    return tokens;
}

Commented version:

function getTokens(){
    var tokens = [];            // new array to hold result
    var query = location.search; // everything from the '?' onward 
    query = query.slice(1);     // remove the first character, which will be the '?' 
    query = query.split('&');   // split via each '&', leaving us an array of something=something strings

    // iterate through each something=something string
    $.each(query, function(i,value){    

        // split the something=something string via '=', creating an array containing the token name and data
        var token = value.split('=');   

        // assign the first array element (the token name) to the 'key' variable
        var key = decodeURIComponent(token[0]);     

        // assign the second array element (the token data) to the 'data' variable
        var data = decodeURIComponent(token[1]);

        tokens[key] = data;     // add an associative key/data pair to our result array, with key names being the URI token names
    });

    return tokens;  // return the array
}

For the examples below we'll assume this address:

http://www.example.com/page.htm?id=4&name=murray

You can assign the URL tokens to your own variable:

var tokens = getTokens();

Then refer to each URL token by name like this:

document.write( tokens['id'] );

This would print "4".

You can also simply refer to a a token name from the function directly:

document.write( getTokens()['name'] );

...which would print "murray".

Prefer answered 15/4, 2014 at 13:9 Comment(0)
G
8

Or if you don't want to reinvent the URI parsing wheel use URI.js

To get the value of a parameter named foo:

new URI((''+document.location)).search(true).foo

What that does is

  1. Convert document.location to a string (it's an object)
  2. Feed that string to URI.js's URI class construtor
  3. Invoke the search() function to get the search (query) portion of the url
    (passing true tells it to output an object)
  4. Access the foo property on the resulting object to get the value

Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/

Gschu answered 16/10, 2014 at 17:31 Comment(0)
O
8

For Single Parameter Value like this index.html?msg=1 use following code,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search.substring(1);
    var varArray = queryString.split("="); //eg. index.html?msg=1

    var param1 = varArray[0];
    var param2 = varArray[1];

}

For All Parameter Value use following Code,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search;
    var varArray = queryString.split("&");
    for (var i=0;i<varArray.length;i++) {
      var param = varArray[i].split("=");
        //parameter-value pair
    }
} 
Outgrow answered 3/3, 2015 at 6:55 Comment(0)
F
8

Here I am posting one example. But it's in jQuery. Hope it will help others:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>

<!-- URL:  www.example.com/correct/?message=done&year=1990-->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')          // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')   // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});
</script>
Fleam answered 25/3, 2015 at 10:50 Comment(1)
Copied from your other post: "Requires the url plugin : plugins.jquery.com/url"Colobus
A
8

I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.

So as an example if we had the following url with the javascript at the bottom in place.

http://TestServer/Pages/NewsArchive.aspx?year=2013&Month=July

All we’d need to do to get the parameters id and page are to call this:

The Code will be:

<script type="text/javascript">
var first = getUrlVars()["year"];
var second = getUrlVars()["Month"];

alert(first);
alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
Acis answered 28/6, 2015 at 4:40 Comment(2)
I don't get why you rolled back my edit of your answer. However you'r welcome to improve it your self :)Afterbrain
Not working for URL like -> ?action=api_call&dates[]=2022-01-28&dates[]=2022-02-03Cilia
L
7
// Read a page's GET URL variables and return them as an associative array.
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;
}

// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];

Got from here: http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html

Like answered 27/7, 2014 at 23:15 Comment(0)
C
7

It's the N++ time I am looking for a clean way to do this.
Will save this here in case I get back cause I know I will... 🙄

const parseUrlQuery = (value) => {
  var urlParams = new URL(value).searchParams
  return Array.from(urlParams.keys()).reduce((acc, key) => {
    acc[key] = urlParams.getAll(key)
    return acc
  }, {})
}

console.log(parseUrlQuery('http://url/path?param1=A&param1=B&param2=ABC&param3=61569'))
Carlisle answered 23/7, 2021 at 12:27 Comment(0)
W
6

Simple way

function getParams(url){
        var regex = /[?&]([^=#]+)=([^&#]*)/g,
            params = {},
            match;
        while(match = regex.exec(url)) {
            params[match[1]] = match[2];
        }
        return params;
    }

then call it like getParams(url)

Waterworks answered 2/9, 2015 at 13:44 Comment(0)
I
6

Elegant, functional style solution

Let's create an object containing URL param names as keys, then we can easily extract the parameter by its name:

// URL: https://example.com/?test=true&orderId=9381  

// Build an object containing key-value pairs
export const queryStringParams = window.location.search
  .split('?')[1]
  .split('&')
  .map(keyValue => keyValue.split('='))
  .reduce<QueryStringParams>((params, [key, value]) => {
    params[key] = value;
    return params;
  }, {});

type QueryStringParams = {
  [key: string]: string;
};


// Return URL parameter called "orderId"
return queryStringParams.orderId;
Interferometer answered 31/7, 2019 at 2:16 Comment(3)
love this, but didn't work for me without making sure to return the accumulator in the reduce functionMaretz
@Maretz it was a typo, there is no way it can work without a returnInterferometer
Looks better now, let's hope you make it to the first page!Maretz
D
5

Here is what I do:

var uriParams = getSearchParameters();
alert(uriParams.c);


// background functions:

// 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;
}
Duplex answered 18/6, 2014 at 18:3 Comment(0)
K
5
// http:localhost:8080/path?param_1=a&param_2=b
var getParamsMap = function () {
    var params = window.location.search.split("&");
    var paramsMap = {};
    params.forEach(function (p) {
        var v = p.split("=");
        paramsMap[v[0]]=decodeURIComponent(v[1]);
    });
    return paramsMap;
};

// -----------------------

console.log(getParamsMap()["param_1"]);  // should log "a"     
Kept answered 16/11, 2016 at 4:5 Comment(1)
This returns the first parameter with '?'Nonprofessional
S
5

This Gist by Eldon McGuinness is by far the most complete implementation of a JavaScript query string parser that I've seen so far.

Unfortunately, it's written as a jQuery plugin.

I rewrote it to vanilla JS and made a few improvements :

function parseQuery(str) {
  var qso = {};
  var qs = (str || document.location.search);
  // Check for an empty querystring
  if (qs == "") {
    return qso;
  }
  // Normalize the querystring
  qs = qs.replace(/(^\?)/, '').replace(/;/g, '&');
  while (qs.indexOf("&&") != -1) {
    qs = qs.replace(/&&/g, '&');
  }
  qs = qs.replace(/([\&]+$)/, '');
  // Break the querystring into parts
  qs = qs.split("&");
  // Build the querystring object
  for (var i = 0; i < qs.length; i++) {
    var qi = qs[i].split("=");
    qi = qi.map(function(n) {
      return decodeURIComponent(n)
    });
    if (typeof qi[1] === "undefined") {
      qi[1] = null;
    }
    if (typeof qso[qi[0]] !== "undefined") {

      // If a key already exists then make this an object
      if (typeof (qso[qi[0]]) == "string") {
        var temp = qso[qi[0]];
        if (qi[1] == "") {
          qi[1] = null;
        }
        qso[qi[0]] = [];
        qso[qi[0]].push(temp);
        qso[qi[0]].push(qi[1]);

      } else if (typeof (qso[qi[0]]) == "object") {
        if (qi[1] == "") {
          qi[1] = null;
        }
        qso[qi[0]].push(qi[1]);
      }
    } else {
      // If no key exists just set it as a string
      if (qi[1] == "") {
        qi[1] = null;
      }
      qso[qi[0]] = qi[1];
    }
  }
  return qso;
}

// DEMO
console.log(parseQuery("?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab"));

See also this Fiddle.

Selfeffacing answered 10/4, 2018 at 13:23 Comment(1)
What I don't understand about javascript is why haven't they made and put url parsing functions into a the language itself or at least in a standards library? low level stuff ilke this shouldn't be reinvented over and over, nor left to developers to utilize whatever entropically variant solutions they will whip up. If this is solid, then something like this should be made into the standard library. This is an example of the type of thing in javascript that turns me off to the language.Meldameldoh
B
5

One liner and IE11 friendly:

> (window.location.href).match('c=([^&]*)')[1]
> "m2-m3-m4-m5"
Bridgid answered 27/6, 2019 at 14:51 Comment(1)
Simplest solution of all.Maurya
B
5

Here's a short and simple function for getting a single param:

function getUrlParam(paramName) {
    var match = window.location.search.match("[?&]" + paramName + "(?:&|$|=([^&]*))");
    return match ? (match[1] ? decodeURIComponent(match[1]) : "") : null;
}

The handling of these special cases are consistent with URLSearchParams:

  • If the parameter is missing, null is returned.

  • If the parameter is present but there is no "=" (e.g. "?param"), "" is returned.

Note! If there is a chance that the parameter name can contain special URL or regex characters (e.g. if it comes from user input) you need to escape it. This can easily be done like this:

function getUrlParamWithSpecialName(paramName) {
    return getUrlParam(encodeURIComponent(paramName).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
}
Bleak answered 13/1, 2020 at 7:42 Comment(0)
H
5
window.location.search.slice(1).split('&').reduce((res, val) => ({...res, [val.split('=')[0]]: val.split('=')[1]}), {})
Hymenium answered 21/7, 2020 at 18:46 Comment(0)
N
4

You can add an input box and then ask the user to copy the value into it...it's really easy that way:

<h1>Hey User! Can you please copy the value out of the location bar where it says like, &m=2? Thanks! And then, if you could...paste it in the box below and click the Done button?</h1>
<input type='text' id='the-url-value' />
<input type='button' value='This is the Done button. Click here after you do all that other stuff I wrote.' />

<script>
//...read the value on click

Ok, seriously though...I found this code and it seems to work good:

http://www.developerdrive.com/2013/08/turning-the-querystring-into-a-json-object-using-javascript/

function queryToJSON() {
    var pairs = location.search.slice(1).split('&');

    var result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });

    return JSON.parse(JSON.stringify(result));
}

var query = queryToJSON();
Nalor answered 25/5, 2014 at 21:38 Comment(0)
P
4
window.location.href.split("?")

then disregard the first index

Array.prototype.slice.call(window.location.href.split("?"), 1) 

returns an array of your url parameters

var paramArray = Array.prototype.slice.call(window.location.href.split(/[?=]+/), 1);
var paramObject = paramArray.reduce(function(x, y, i, a){ (i%2==0) ?  (x[y] = a[i+1]) : void 0; return x; }, {});

A bit more verbose/hacky but also functional, paramObject contains all parameters mapped as a js object

Plenipotentiary answered 18/11, 2014 at 11:38 Comment(0)
D
4

Here is the angularJs source code for parsing url query parameters into an Object :

function tryDecodeURIComponent(value) {
  try {
    return decodeURIComponent(value);
  } catch (e) {
    // Ignore any invalid uri component
  }
}

function isDefined(value) {return typeof value !== 'undefined';}

function parseKeyValue(keyValue) {
  keyValue = keyValue.replace(/^\?/, '');
  var obj = {}, key_value, key;
  var iter = (keyValue || "").split('&');
  for (var i=0; i<iter.length; i++) {
    var kValue = iter[i];
    if (kValue) {
      key_value = kValue.replace(/\+/g,'%20').split('=');
      key = tryDecodeURIComponent(key_value[0]);
      if (isDefined(key)) {
        var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
        if (!hasOwnProperty.call(obj, key)) {
          obj[key] = val;
        } else if (isArray(obj[key])) {
          obj[key].push(val);
        } else {
          obj[key] = [obj[key],val];
        }
      }
    }
  };
  return obj;
}

alert(JSON.stringify(parseKeyValue('?a=1&b=3&c=m2-m3-m4-m5')));

You can add this function to window.location:

window.location.query = function query(arg){
  q = parseKeyValue(this.search);
  if (!isDefined(arg)) {
    return q;
  }      
  if (q.hasOwnProperty(arg)) {
    return q[arg];
  } else {
    return "";
  }
}

// assuming you have this url :
// http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5

console.log(window.location.query())

// Object {a: "1", b: "3", c: "m2-m3-m4-m5"}

console.log(window.location.query('c'))

// "m2-m3-m4-m5"
Delija answered 19/5, 2015 at 14:43 Comment(0)
H
4

We can get the c parameter values in a simpler way without looping all the parameters, see the below jQuery to get the parameters.

1. To Get the Parameter value:

var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";

url.match(**/(c=)[0-9A-Za-z-]+/ig**)[0].replace('c=',"")

(or)

url.match(**/(c=)[0-z-]+/ig**)[0].replace('c=',"")

returns as a string

"m2-m3-m4-m5"

2. To Replace the parameter value:

var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";

url.replace(**/(c=)[0-9A-Za-z-]+/ig, "c=m2345"**)
Hedvig answered 1/10, 2016 at 16:14 Comment(1)
Where is the jQuery. Could you just name it JS if it's JS because there is no jquery.Slop
G
3

I like writing shorthand as much as possible:

URL: example.com/mortgage_calc.htm?pmts=120&intr=6.8&prin=10000

Vanilla Javascript:

for ( var vObj = {}, i=0, vArr = window.location.search.substring(1).split('&');
        i < vArr.length; v = vArr[i++].split('='), vObj[v[0]] = v[1] ){}
// vObj = {pmts: "120", intr: "6.8", prin: "10000"}
Gilleod answered 25/3, 2014 at 17:31 Comment(0)
M
3
function getParamValue(param) {
    var urlParamString = location.search.split(param + "=");
    if (urlParamString.length <= 1) return "";
    else {
        var tmp = urlParamString[1].split("&");
        return tmp[0];
    }
}

This should work for your case no matter the param is last or not.

Manizales answered 19/11, 2015 at 18:8 Comment(0)
C
3

You can simply use core javascript to get the param's key value as a js object:

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
let obj = {};
var c = url.searchParams.forEach((value, key) => {
  obj[key] = value;
});
console.log(obj);
Consignee answered 15/2, 2019 at 11:52 Comment(1)
The URL object is (a) already mentioned in the accepted answer and (b) is not "core javascript". It is defined in its own standard and isn't supported by IE.Vallievalliere
F
3

To extract all url params from search object in window.location as json

export const getURLParams = location => {
    const searchParams = new URLSearchParams(location.search)
    const params = {}

    for (let key of searchParams.keys()) {
        params[key] = searchParams.get(key)
    }

    return params
}

console.log(getURLParams({ search: '?query=someting&anotherquery=anotherthing' }))

// --> {query: "someting", anotherquery: "anotherthing"}
Flexure answered 28/3, 2019 at 11:32 Comment(0)
H
2

Here's a solution I find a little more readable -- but it will require a .forEach() shim for < IE8:

var getParams = function () {
  var params = {};
  if (location.search) {
    var parts = location.search.slice(1).split('&');

    parts.forEach(function (part) {
      var pair = part.split('=');
      pair[0] = decodeURIComponent(pair[0]);
      pair[1] = decodeURIComponent(pair[1]);
      params[pair[0]] = (pair[1] !== 'undefined') ?
        pair[1] : true;
    });
  }
  return params;
}
Halliday answered 2/10, 2013 at 7:35 Comment(0)
C
2

Here is my solution: jsfiddle

The method below returns a dictionary containing the parameters of the given URL. In case there are no paramters it will be null.

function getParams(url){
    var paramsStart = url.indexOf('?');
    var params = null;

    //no params available
    if(paramsStart != -1){
        var paramsString = url.substring(url.indexOf('?') + 1, url.length);

        //only '?' available
        if(paramsString != ""){
            var paramsPairs = paramsString.split('&');

            //preparing
            params = {};
            var empty = true;
            var index  = 0;
            var key = "";
            var val = "";

            for(i = 0, len = paramsPairs.length; i < len; i++){
                index = paramsPairs[i].indexOf('=');

                //if assignment symbol found
                if(index != -1){
                    key = paramsPairs[i].substring(0, index);
                    val = paramsPairs[i].substring(index + 1, paramsPairs[i].length);

                    if(key != "" && val != ""){

                        //extend here for decoding, integer parsing, whatever...

                        params[key] = val;

                        if(empty){
                            empty = false;
                        }
                    }                    
                }
            }

            if(empty){
                params = null;
            }
        }
    }

    return params;
}
Coatee answered 12/6, 2014 at 15:29 Comment(0)
E
2

Use dojo. No other solution on here is this short or as well-tested:

require(["dojo/io-query"], function(ioQuery){
    var uri = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ";
    var query = uri.substring(uri.indexOf("?") + 1, uri.length);
    var queryObject = ioQuery.queryToObject(query);
    console.log(queryObject.c); //prints m2-m3-m4-m5
});
Eunaeunice answered 3/10, 2014 at 22:55 Comment(0)
D
2

PHP parse_str copycat.. :)

// Handles also array params well
function parseQueryString(query) {
    var pars = (query != null ? query : "").replace(/&+/g, "&").split('&'),
        par, key, val, re = /^([\w]+)\[(.*)\]/i, ra, ks, ki, i = 0,
        params = {};

    while ((par = pars.shift()) && (par = par.split('=', 2))) {
        key = decodeURIComponent(par[0]);
        // prevent param value going to be "undefined" as string
        val = decodeURIComponent(par[1] || "").replace(/\+/g, " ");
        // check array params
        if (ra = re.exec(key)) {
            ks = ra[1];
            // init array param
            if (!(ks in params)) {
                params[ks] = {};
            }
            // set int key
            ki = (ra[2] != "") ? ra[2] : i++;
            // set array param
            params[ks][ki] = val;
            // go on..
            continue;
        }
        // set param
        params[key] = val;
    }

    return params;
}

var query = 'foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last';
var params = parseQueryString(query);
console.log(params)
console.log(params.foo)        // 1
console.log(params.bar)        // The bar!
console.log(params.arr[0])     // a0
console.log(params.arr[1])     // a1
console.log(params.arr.s)      // as
console.log(params.arr.none)   // undefined
console.log("isset" in params) // true like: isset($_GET['isset'])



/*
// in php
parse_str('foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last', $query);
print_r($query);

Array
(
    [foo] => 1
    [bar] => The bar!
    [arr] => Array
        (
            [0] => a0
            [1] => a1
            [s] => as
            [2] => last
        )

    [isset] =>
)*/
Dumpy answered 25/12, 2014 at 20:7 Comment(0)
W
2

Try

url.match(/[?&]c=([^&]*)/)[1]

var url = "www.test.com/t.html?a=1&bc=3&c=m2-m3-m4-m5";

c= url.match(/[?&]c=([^&]*)/)[1];

console.log(c);

This is improvement of Daniel Sokolowski answer Jun 27 '19. Regexp explanation

  • [?&] first matched character must be ? or & (to omit param like ac=)
  • c= name of parameter with = char at end
  • (...) match in first group
  • [^&]* zero or more characters ( * ) different (^) than &
  • [1] choose first group from array of matches
Waldgrave answered 17/1, 2020 at 13:18 Comment(0)
S
2

simplified version, tested

function get(name){
    var r = /[?&]([^=#]+)=([^&#]*)/g,p={},match;
    while(match = r.exec(window.location)) p[match[1]] = match[2];
    return p[name];
}

usage:

var parameter = get['parameter']

Subterranean answered 11/10, 2020 at 23:39 Comment(0)
L
1

I prefer to use available resources rather than reinventing how to parse those params.

  1. Parse the URL as an object
  2. Extract the search params part
  3. Transform the searchParams from an Iterator to an Array with array expansion.
  4. Reduce the key-value array into an object.

const url = 'http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';
const params = [... new URL(url).searchParams.entries()]
  .reduce((a, c) => Object.assign(a, {[c[0]]:c[1]}), {})

console.log(params);
Lithe answered 2/10, 2018 at 16:16 Comment(1)
I've posted an answer that solves the question in a simple and modern way. I'd like to have some feedback if my question is downvoted. Where was I wrong? Is it conceptual or practical? Could it be fixed in the answer? Please, provide feedback!Lithe
P
1
function parseUrl(url){
    let urlParam = url.split("?")[1];
    console.log("---------> URL param : " + urlParam);
    urlParam = urlParam.split("&");
    let urlParamObject = {};
    for(let i=0;i < urlParam.length;i++){
        let tmp = urlParam[i].split("=");
        urlParamObject[tmp[0]] = tmp[1];
    }
    return urlParamObject;
}

let param = parseUrl(url);
param.a // output 10
param.b // output 20
Pacemaker answered 9/3, 2019 at 6:43 Comment(0)
C
1

Get a single param value:

function getQueryParameter(query, parameter) {
return (window.location.href.split(parameter + '=')[1].split('&')[0]);}
Cloverleaf answered 31/5, 2019 at 8:48 Comment(0)
C
1

you can do it by bellow function:

function getParameter(parameterName){
        let paramsIndex = document.URL.indexOf("?");
        let params="";
        if(paramsIndex>0)
            params=document.URL.substring(paramsIndex+1, document.URL.length).split("&");
        let result = [];
        for(let i=0;i<params.length;i++)
        {
            console.warn(params[i].split("=")[0].toString()+ "," + params[i].split("=")[1].toString());
            var obj = {"key":params[i].split("=")[0].toString(),"value":params[i].split("=")[1].toString()};
            result.push(obj);
        }
        return passedValue = result.find(x=>x.key==parameterName).value;
    }

now you can get parameter value with getParameter("parameterName")

Clisthenes answered 11/10, 2020 at 21:21 Comment(0)
A
0

Learning from many answers (like VaMoose's, Gnarf's or Blixt's).

You can create an object (or use the Location object) and add a method that allows you to get the URL parameters, decoded and with JS style:

Url = {
    params: undefined,
    get get(){
        if(!this.params){
            var vars = {};
            if(url.length!==0)
                url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
                    key=decodeURIComponent(key);
                    if(typeof vars[key]==="undefined") {
                        vars[key]= decodeURIComponent(value);
                    }
                    else {
                        vars[key]= [].concat(vars[key], decodeURIComponent(value));
                    }
                });
            this.params = vars;
        }
        return this.params;
    }
};

This allows the method to be called just using Url.get.

The first time it will fetch the object from the url, next times it will load the saved ones.

Example

In a url like ?param1=param1Value&param2=param2Value&param1=param1Value2, parameters can be fetched like:

Url.get.param1 //["param1Value","param1Value2"]
Url.get.param2 //"param2Value"
Akins answered 28/1, 2015 at 21:26 Comment(0)
A
0
$_GET: function (param) {
    var regex = new RegExp("(?:[?&]+" + param + "=)([^&]*)?", "i");
    var match = regex.exec(window.location.href);
    return match === null ? match : match[1];
}
Achromat answered 30/3, 2016 at 8:35 Comment(1)
I have noticed that if you send the parameter with '?' at it's beginning it still understands that its the parameter. was it intended ?Nonprofessional
R
0

This works:

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

I didn't get any of the other top answers to work.

Reincarnate answered 7/10, 2016 at 17:1 Comment(1)
This code is very helpful and I still use it a lot.Coffin
O
0

I developed a JavaScript tool to do this in one easy step

First, copy this script link into the head of your HTML:

<script src="https://booligoosh.github.io/urlParams/urlParams.js"></script>

Then simply get the value of c using urlParams.c or urlParams['c']. Simple!

You can see a real demo using your values here.

Also keep in mind that I did develop this, but it's an easy and carefree solution to your problem. This tool also includes hex character decoding, which can often be helpful.

Occupation answered 22/5, 2017 at 9:16 Comment(0)
C
0

you can run this function

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

    var source = getUrlVars()["lm_supplier"];
    var el = source.toString();
    var result= decodeURI(el);

console.log(result)

this function get what you want from the url, var source = getUrlVars()["put what you want to get from the url"];

Cerebrate answered 5/11, 2017 at 13:42 Comment(0)
L
0
    function gup() {
    var qs = document.location.search;
    qs = qs.split('+').join(' ');
    var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g;
    while (tokens = re.exec(qs))
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    return params;
}

use it like

var params = gup()

and then

params.param1
params.param2
Louisville answered 7/11, 2017 at 7:21 Comment(0)
L
0

As mentioned in the first answer in the latest browser we can use new URL api, However a more consistent native javascript easy solution to get all the params in an object and use them could be

For Example this class say locationUtil

const locationSearch = () => window.location.search;
const getParams = () => {
  const usefulSearch = locationSearch().replace('?', '');
  const params = {};
  usefulSearch.split('&').map(p => {
    const searchParam = p.split('=');
    const [key, value] = searchParam;
    params[key] = value;
    return params;
  });
  return params;
};

export const searchParams = getParams();

Usage :: Now you can import searchParams object in your class

for Example for url --- https://www.google.com?key1=https://www.linkedin.com/in/spiara/&valid=true

import { searchParams } from '../somewhere/locationUtil';

const {key1, valid} = searchParams;
if(valid) {
 console.log("Do Something");
 window.location.href = key1;
}
Laevorotation answered 15/1, 2019 at 12:43 Comment(0)
T
-1

In my case ( redirect to new domain with all sub url )::

window.location.replace("https://newdomain.com" + window.location.pathname);
Torrential answered 29/3, 2018 at 19:20 Comment(0)
F
-1

I tried a lot of different ways, but this tried and true regex function works for me when I am looking for param values in a URL, hope this helps:

        var text = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5'

        function QueryString(item, text){
            var foundString = text.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
            return foundString ? foundString[1] : foundString;
        }

        console.log(QueryString('c', text));

use like QueuryString('param_name', url) and will return the value

m2-m3-m4-m5

Frances answered 13/7, 2018 at 9:20 Comment(0)
D
-1

My solution:

/**
 * get object with params from query of url
 */
const getParams = (url) => {
  const params = {};
  const parser = document.createElement('a');
  parser.href = url;
  const query = parser.search.substring(1);
  if (query !== '') {
    const vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split('=');
      const key = decodeURIComponent(pair[0]).replace('[]', '');
      const value = decodeURIComponent(pair[1]);
      
      if (key in params) {
        if (Array.isArray(params[key])) {
          params[key].push(value);
        } else {
          params[key] = [params[key]];
          params[key].push(value);
        }
      } else params[key] = value;
    }
  }
  return params;
}
Disappearance answered 27/3, 2021 at 7:44 Comment(0)
T
-2

I have had the same problem over and over again. Now many users here now I'm famous for my HAX work,

so I solve it by using:

PHP:

echo "<p style="display:none" id=\"hidden-GET\">".$_GET['id']."</p>";

JS:

document.getElementById("hidden-GET").innerHTML;

Simple HAX but working.

Tilla answered 19/9, 2018 at 17:40 Comment(2)
Danger: This features a reflected XSS vulnerability.Vallievalliere
You can prevent the XSS by using htmlspecialchars($_GET['id']) instead.Misguided

© 2022 - 2025 — McMap. All rights reserved.