InTry
InTry

Reputation: 1169

Matching part of the string using or operator

The URL string may look like:

http://test.com/index.php?page=xxx&item=51

or

http://test.com/index.php?page=xxx&object=22&bla=14

or

http://test.com/index.php?page=xxx

How I would be able to capture word xxx?

Tried something like this:

url_string.match(/\b\?page\=(.*)(\&|$)/)

Upvotes: 0

Views: 50

Answers (3)

anubhava
anubhava

Reputation: 785098

You can simplify your regex a lot like this:

var matches = url_string.match(/\?page=([^&\n]*)/i);

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174706

Usually * does a greedy match, you need to add a reluctant quantifier ? just after to * to do a shortest possible match.

url_string.match(/\?page\=(.*?)(?:\&|$)/gm)

Group index 1 contains the value of page

DEMO

Upvotes: 1

arco444
arco444

Reputation: 22821

You can use:

url_string.match(/\?page=([^&]+)/)

DEMO

Upvotes: 2

Related Questions