Capture value out of query string with regex?

90,146

Solution 1

/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.

Solution 2

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=([^&#]*)/

Solution 3

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 

Solution 4

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, " "));
}

Solution 5

The following should work:

\?name=(.*?)&
Share:
90,146
Trip
Author by

Trip

I program Ruby, C#, iOS, Node, and Augmented Reality for Unity3D. I write PostgreSQL, mySQL, SQLite, and MongoDB. I use Heroku, Amazon, Microsoft Azure. Creator of the Yoga Sutras App, Braidio Mobile, and Braidio. In my spare time, I teach Ashtanga Yoga. elephant trip AT gmail DOT com #happyToHelp

Updated on July 09, 2022

Comments

  • Trip
    Trip almost 2 years

    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.

    • Admin
      Admin about 12 years
      What does ^ do? What would prevent it from working?
    • Álvaro González
      Álvaro González about 12 years
    • Trip
      Trip about 12 years
      Way overkill Alvaro. And definately not the answer I'm looking for.
  • Trip
    Trip about 12 years
    This captures name= I want just what would appear after name= and before the &
  • Trip
    Trip about 12 years
    Hmm this captures ?name= and I just want what would come after name= and before &
  • vol7ron
    vol7ron about 12 years
    Show the rest of your code. If you assign it to an array, the array will contain matches, otherwise you'll have to use RegExp.$1
  • Trip
    Trip about 12 years
    @pst.. I am not RegEx master yet. :( You mean by variables like $1 or $2 ? I think this example only returns one group
  • Trip
    Trip about 12 years
    In regards to last update, I'm getting that's not possible to make a regex statement that picks something after a specific character and before another character. Suppose this wasn't a URL and was just a string?
  • vol7ron
    vol7ron about 12 years
    @Trip: no, the first regex works, you never said how you're assigning it.
  • Trip
    Trip about 12 years
    Ah my apologies, vol7ron. :D Terribly sorry. I'm trying to do a replace. I'll update my question.
  • vol7ron
    vol7ron about 12 years
    @Trip: listed the match example for how to assign. Note that if matches doesn't match anything, it'll be null.
  • vol7ron
    vol7ron about 12 years
    The function might be overkill, but its necessary if you have duplicate keys, like name=J&name=K, which is valid. Even if there's only one, I still put it in an array so I can handle the results the same way. Example for (var n=params['name'].length;n--){ /*... do something with params['name'][n] ... */ } which will only fail if the key never existed at all.
  • vhs
    vhs over 10 years
    The condensed example will miss the final match in the string presented unless a '&' is affixed at the end of the query string.
  • vol7ron
    vol7ron about 10 years
    @JoshH I'm assuming the condensed example is the first 3-line block of code. I don't think what you're saying is correct: "/pages/new?name=J".match(/name=([^&]*)/)[1]; returns "J" and there is no ampersand. My getParams function should also work as expected. I think you would need to show an example to see what trouble you've encountered -- also note that it's possible that IE handles regexs different, in case you are using that.
  • help-info.de
    help-info.de about 3 years
    There are other answers (and a accepted one) that provide the OP's question, and they were posted some time ago. When posting an answer see: How do I write a good answer?, please make sure you add either a new solution, or a substantially better explanation, especially when answering older questions.
  • Yeats
    Yeats over 2 years
    The "better way" is just terrible, non-working code.