46

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.

Trip
  • 26,756
  • 46
  • 158
  • 277

9 Answers9

89

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

vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • 1
    This captures `name=` I want just what would appear after `name=` and before the `&` – Trip Apr 12 '12 at 15:41
  • 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` – vol7ron Apr 12 '12 at 15:42
  • 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? – Trip Apr 12 '12 at 15:52
  • @Trip: no, the first regex works, you never said how you're assigning it. – vol7ron Apr 12 '12 at 15:53
  • 1
    Ah my apologies, vol7ron. :D Terribly sorry. I'm trying to do a replace. I'll update my question. – Trip Apr 12 '12 at 15:56
  • 1
    @Trip: listed the match example for how to assign. Note that if `matches` doesn't match anything, it'll be null. – vol7ron Apr 12 '12 at 16:03
  • 1
    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. – vol7ron Apr 12 '12 at 16:14
  • The condensed example will miss the final match in the string presented unless a '&' is affixed at the end of the query string. – vhs Mar 03 '14 at 02:24
  • @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. – vol7ron Mar 28 '14 at 16:07
13

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=([^&#]*)/
William Neely
  • 1,923
  • 1
  • 20
  • 23
12

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 
cruzanmo
  • 747
  • 8
  • 8
4
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'
Phil H
  • 19,928
  • 7
  • 68
  • 105
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, " "));
}
Bishoy Hanna
  • 4,539
  • 1
  • 29
  • 31
2

The following should work:

\?name=(.*?)&
Karl Barker
  • 11,095
  • 3
  • 21
  • 26
  • 1
    Hmm this captures `?name=` and I *just* want what would come after `name=` and before `&` – Trip Apr 12 '12 at 15:42
  • 2
    @pst.. I am not RegEx master yet. :( You mean by variables like $1 or $2 ? I think this example only returns one group – Trip Apr 12 '12 at 15:45
2

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

(document.location.search.match(/[?&]name=([^&]+)/)||[null,null])[1]

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.

HungryBeagle
  • 262
  • 1
  • 13
0

You can get the same result with simple .split() in javascript.

let value = url.split("name=")[1].split("&")[0];

-1

This might work:

\??(.*=.+)*(&.*=.+)?
Hisoka
  • 1
  • 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?](https://stackoverflow.com/help/how-to-answer), please make sure you add either a new solution, or a substantially better explanation, especially when answering older questions. – help-info.de May 27 '21 at 17:50