-1

I need a Regular Expression which can meet my request below:

  1. It can get characters between 'id=' and '&'
  2. the character '&' may exist or not

here's a example, say I have two URL like below:

  1. http://example.com?id=222&haha=555
  2. http://example.com?id=222

The Regular Expression can get the key id's value 222 in both URL.

VERY THANKFUL if someone can help me solve this problem!!!

Tamud Gu
  • 31
  • 6

2 Answers2

0

You could try the below regex to get the id value whether it is followed by a & symbol or line end $.

id=(.*?)(?=&|$)

The captured value was stored inside the group index 1.

DEMO

> var re = /id=(.*?)(?=&|$)/g;
undefined
> var str = 'http://example.com?id=222&haha=555';
undefined
> var m;
undefined
> while ((m = re.exec(str)) != null) {
...     console.log(m[1]);
... }
222
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Not the regexp way but this should also work

str.split("id=")[1].split('&')[0]
Mritunjay
  • 25,338
  • 7
  • 55
  • 68