Capture value out of query string with regex?

I am trying to select just what comes after name= and before the & in :

"/pages/new?name=J&return_url=/page/new"

So far I have..

^name=(.*?).

I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.

The end case situation would be allowing myself to do a replace statement on this dynamic variable found by regex.


/name=([^&]*)/

  • remove the ^ and end with an &

Example:

var str     = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);

The better way is to break all the params down (Example using current address):

function getParams (str) {
   var queryString = str || window.location.search || '';
   var keyValPairs = [];
   var params      = {};
   queryString     = queryString.replace(/.*?\?/,"");

   if (queryString.length)
   {
      keyValPairs = queryString.split('&');
      for (pairNum in keyValPairs)
      {
         var key = keyValPairs[pairNum].split('=')[0];
         if (!key.length) continue;
         if (typeof params[key] === 'undefined')
         params[key] = [];
         params[key].push(keyValPairs[pairNum].split('=')[1]);
      }
   }
   return params;
}


var url    = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];

Update

Though still not supported in any version of IE, URLSearchParams provides a native way of retrieving values for other browsers.


The accepted answer includes the hash part if there is a hash right after the params. As @bishoy has in his function, the correct regex would be

/name=([^&#]*)/

Improving on previous answers:

/**
 *
 * @param {string} name
 * @returns {string|null}
 */
function getQueryParam(name) {
  var q = window.location.search.match(new RegExp('[?&]' + name + '=([^&#]*)'));
  return q && q[1];
}

getQueryParam('a'); // returns '1' on page http://domain.com/page.html?a=1&b=2 

here is the full function (tested and fixed for upper/lower case)

function getParameterByName (name) 
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name.toLowerCase() + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search.toLowerCase());
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

The following should work:

\?name=(.*?)&