Capture value out of query string with regex?

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


So far I have..


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.




  • remove the ^ and end with an &


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

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

function getParams (str) {
   var queryString = str || || '';
   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] = [];
   return params;

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


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


Improving on previous answers:

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

getQueryParam('a'); // returns '1' on page 

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


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(;
    if (results == null)
        return "";
        return decodeURIComponent(results[1].replace(/\+/g, " "));

The following should work:

var myname = str.match(/\?name=([^&]+)&/)[1];

The [1] is because you apparently want the value of the group (the part of the regex in brackets).

var str = "/pages/new?name=reaojr&return_url=/page/new";
var matchobj = str.match(/\?name=([^&]+)&/)[1];
document.writeln(matchobj); // prints 'reaojr'

Here's a single line answer that prevents having to store a variable (if you can't use URLSearchParams because you still support IE)


By adding in the ||[null,null] and surrounding it in parentheses, you can safely index item 1 in the array without having to check if match came back with results. Of course, you can replace the [null,null] with whatever you'd like as a default.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.