0

I am trying to target ?state=wildcard in this statement :

?state=uncompleted&dancing=yes

I would like to target the entire line ?state=uncomplete, but also allow it to find whatever word would be after the = operator. So uncomplete could also be completed, unscheduled, or what have you.

A caveat I am having is granted I could target the wildcard before the ampersand, but what if there is no ampersand and the param state is by itself?

Trip
  • 26,756
  • 46
  • 158
  • 277
  • possible duplicate of [Get query string values in JavaScript](http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript) – Juicy Scripter Mar 04 '12 at 16:34

4 Answers4

5

Try this regular expression:

var regex = /\?state=([^&]+)/;
var match = '?state=uncompleted&dancing=yes'.match(regex);
match; // => ["?state=uncompleted", "uncompleted"]

It will match every character after the string "\?state=" except an ampersand, all the way to the end of the string, if necessary.

maerics
  • 151,642
  • 46
  • 269
  • 291
2

Alternative regex: /\?state=(.+?)(?:&|$)/

It will match everything up to the first & char or the end of the string

pomeh
  • 4,742
  • 4
  • 23
  • 44
2

IMHO, you don't need regex here. As we all know, regexes tend to be slow, especially when using look aheads. Why not do something like this:

var URI = '?state=done&user=ME'.split('&');
var passedVals = [];

This gives us ['?state=done','user=ME'], now just do a for loop:

for (var i=0;i<URI.length;i++)
{
    passedVals.push(URI[i].split('=')[1]);
}

Passed Vals wil contain whatever you need. The added benefit of this is that you can parse a request into an Object:

var URI = 'state=done&user=ME'.split('&');
var urlObjects ={};
for (var i=0;i<URI.length;i++)
{
    urlObjects[URI[i].split('=')[0]] = URI[i].split('=')[1];
}

I left out the '?' at the start of the string, because a simple .replace('?','') can fix that easily...

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
1

You can match as many characters that are not a &. If there aren't any &s at all, that will of course also work:

/(\?state=[^&]+)/.exec("?state=uncompleted");
/(\?state=[^&]+)/.exec("?state=uncompleted&a=1");

// both: ["?state=uncompleted", "?state=uncompleted"]
pimvdb
  • 151,816
  • 78
  • 307
  • 352