How can I get a specific parameter from [duplicate]

If I had a URL such as


How would I write a JavaScript function to grab the variable year and see if it contains anything?

I know it can be done with but I can’t figure out how it grabs parameters.



My favorite way for getting URL params is this approach:

var parseQueryString = function() {

    var str =;
    var objURL = {};

        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){
            objURL[ $1 ] = $3;
    return objURL;

//Example how to use it: 
var params = parseQueryString();

A non-regex approach, you can simply split by the character '&' and iterate through the key/value pair:

function getParameter(paramName) {
  var searchString =,
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return val[1];
  return null;

2020 EDIT:

Nowadays, in modern browsers you can use the URLSearchParams constructor:

const params = new URLSearchParams('?year=2020&month=02&day=01')

// You can access specific parameters:

// And you can iterate over all parameters
for (const [key, value] of params) {
  console.log(`Key: ${key}, Value: ${value}`);


The following uses regular expressions and searches only on the query string portion of the URL.

Most importantly, this method supports normal and array parameters as in http://localhost/?fiz=zip&foo[]=!!=&bar=7890#hashhashhash

function getQueryParam(param) {
    var result =
        new RegExp("(\\?|&)" + param + "(\\[\\])?=([^&]*)")

    return result ? result[3] : false;




It took me a while to find the answer to this question. Most people seem to be suggesting regex solutions. I strongly prefer to use code that is tried and tested as opposed to regex that I or someone else thought up on the fly.

I use the parseUri library available here:

It allows you to do exactly what you are asking for:

var uri = 'http://localhost/search.php?year=2008';
var year = uri.queryKey['year'];
// year = '2008'

A Simple One-Line Solution:

let query = Object.assign.apply(null,'&').map(entry => ({ [entry.split('=')[0]]: entry.split('=')[1] })));

Expanded & Explained:

// define variable
let query;

// fetch source query
query =;

// skip past the '?' delimiter
query = query.slice(1);

// split source query by entry delimiter
query = query.split('&');

// replace each query entry with an object containing the query entry
query = => {

   // get query entry key
   let key = entry.split('=')[0];

   // get query entry value
   let value = entry.split('=')[1];

   // define query object
   let container = {};

   // add query entry to object
   container[key] = value;

   // return query object
   return container;

// merge all query objects
query = Object.assign.apply(null, query);

I used a variant of Alex's - but needed to to convert the param appearing multiple times to an array. There seem to be many options. I didn't want rely on another library for something this simple. I suppose one of the other options posted here may be better - I adapted Alex's because of the straight forwardness.

parseQueryString = function() {
    var str =;
    var objURL = {};

    // local isArray - defer to underscore, as we are already using the lib
    var isArray = _.isArray

        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){

            if(objURL[ $1 ] && !isArray(objURL[ $1 ])){
                // if there parameter occurs more than once, convert to an array on 2nd
                var first = objURL[ $1 ]
                objURL[ $1 ] = [first, $3]
            } else if(objURL[ $1 ] && isArray(objURL[ $1 ])){
                // if there parameter occurs more than once, add to array after 2nd
                objURL[ $1 ].push($3)
                // this is the first instance
                objURL[ $1 ] = $3;

    return objURL;

I played a bit with this problem and at this end I used this:

function getJsonFromUrl() {
  return Object.assign("&").map(sliceProperty));
  • Object.assign to transform a list of object into one object
  • Spread operator ... to transform an array into a list
  •"&") to get all parameters as array of properties (foo=bar)
  • map walk each properties and split them into an array (either call splitProperty or sliceProperty).


  function splitProperty(pair) {
    [key, value] = pair.split("=")
    return { [key]: decodeURIComponent(value) }
  • Split by =
  • Deconstruct the array into an array of two elements
  • Return a new object with the dynamic property syntax


  function sliceProperty(pair) {
    const position = pair.indexOf("="),
      key = pair.slice(0, position),
      value = pair.slice(position + 1, pair.length);
    return { [key]: decodeURIComponent(value) }
  • Set the position of =, key and value
  • Return a new object with the dynamic property syntax

I think splitProperty is prettier but sliceProperty is faster. Run JsPerf for more information.


Grab the params from with one line:

const params = new Map('&').map(param => param.split('=')))

Then, simply:

  //year exists. do something...
} else {
  //year doesn't exist. do something else...

ES6 answer:

const parseQueryString = (path = =>
  path.slice(1).split('&').reduce((car, cur) => {
   const [key, value] = cur.split('=')
   return {, [key]: value } 
  }, {})

for example:

// => {foo: "bar", foobar: "baz"}

This is what I like to do:
        function(accumulator, currentValue) {
            var pair = currentValue
                .map(function(value) {
                    return decodeURIComponent(value);

            accumulator[pair[0]] = pair[1];

            return accumulator;

Of course you can make it more compact using modern syntax or writing everything into one line...

I leave that up to you.


You may use window.URL class:

new URL(location.href).searchParams.get('year')
// Returns 2008 for href = "http://localhost/search.php?year=2008".
// Or in two steps:
const params = new URL(location.href).searchParams;
const year = params.get('year');

This question is old and things have evolved in JavaScript. You can now do this:

const params = {}'&').forEach(pair => {
  [key, value] = pair.split('=')
  params[key] = value

and you get params.year that contains 2008. You would also get other query params in your params object.

Edit: a shorter/cleaner way to do this:

const params = new Map('&').map(kv => kv.split('=')))

You can then test if the year param exists with:

params.has('year')  // true

Or retrieve it with:

params.get('year')  // 2008
function gup( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
        return results[1];
var year = gup("year"); // returns "2008"

The easiest way is to have

if ('yourtext=') >= 0) {
    // your code
} else {
    // what happens?


The indexOf(text) function returns

  • A WHOLE NUMBER BELOW 0 when the text passed in the function is not in whatever variable or string you are looking for - in this case
  • A WHOLE NUMBER EQUAL TO 0 OR HIGHER when the text passed in the function is in whatever variable or string you are looking for - in this case

I hope this was useful, @gumbo


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.