Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a specific parameter from location.search? [duplicate]

Tags:

javascript

url

People also ask

What does location search return?

location.search returns a query string including the initial question mark.

What is URLSearchParams?

The URLSearchParams interface defines utility methods to work with the query string of a URL.


My favorite way for getting URL params is this approach:

var parseQueryString = function() {

    var str = window.location.search;
    var objURL = {};

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

//Example how to use it: 
var params = parseQueryString();
alert(params["foo"]); 

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

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

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      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:
console.log(params.get('year'))
console.log(params.get('month'))

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

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

const params = {}
document.location.search.substr(1).split('&').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(location.search.slice(1).split('&').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

Edit 2020

You can convert URL params to an Object:

const params = location.search.slice(1).split('&').reduce((acc, s) => {
  const [k, v] = s.split('=')
  return Object.assign(acc, {[k]: v})
}, {})

Then it can be used as a regular JS Object:

params.year  // 2008

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 =  window.location.search.match(
        new RegExp("(\\?|&)" + param + "(\\[\\])?=([^&]*)")
    );

    return result ? result[3] : false;
}

console.log(getQueryParam("fiz"));
console.log(getQueryParam("foo"));
console.log(getQueryParam("bar"));
console.log(getQueryParam("zxcv"));

Output:

zip
!!=
7890
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: http://stevenlevithan.com/demo/parseuri/js/

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'

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 "";
    else
        return results[1];
}
var year = gup("year"); // returns "2008"