Trip
Trip

Reputation: 27114

Can regex matches in javascript match any word after an equal operator?

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?

Upvotes: 0

Views: 3987

Answers (4)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

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

Upvotes: 2

pomeh
pomeh

Reputation: 4912

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

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

Upvotes: 2

pimvdb
pimvdb

Reputation: 154838

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"]

Upvotes: 1

maerics
maerics

Reputation: 156434

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.

Upvotes: 5

Related Questions