17

Possible Duplicate:
How can I get query string values?

Trying to get a regex (Javascript).

Input:   url.html?id=14114&yolo=hahaha
Output:  id=14114
         yolo=hahaha

So this is what i have done so far: (\&|\?)(.*?)\=(.*?)

How do I also include the red circled regions?

enter image description here

Community
  • 1
  • 1
Mathew Kurian
  • 5,949
  • 5
  • 46
  • 73

2 Answers2

41

How about this pattern:

(\?|\&)([^=]+)\=([^&]+)
Sina Iravanian
  • 16,011
  • 4
  • 34
  • 45
  • 2
    I made a change after he posted. with his help: (\?|\&)([^=]+)\=([^\&]+) – Mathew Kurian Feb 04 '13 at 01:02
  • I know this is a little late but this answer will not ignore url fragments (anything after the "#"). Try this one: /[(\?|\&)]([^=]+)\=([^]+)/g – webwires Nov 12 '15 at 16:19
  • 6
    As in the RFC: https://tools.ietf.org/html/rfc3986#section-3.3 The semicolon(';') character can also be used to delimit parameters, So I think regex pattern should be changed accordingly – TMKasun May 27 '16 at 12:49
  • 2
    @TMKasun is right, the expression should match "Matrix-Parameters" too! `(?:\?|&|;)([^=]+)=([^&|;]+)` – Frozen_byte Mar 01 '18 at 15:03
  • No, it is doesn't work. For example: "url.com?a=bat & man", -> (a=bat, &man) (?) – Franco Gil Feb 03 '21 at 13:02
  • This pattern assumes param values are nonempty, for example it won't match `a=` in `url.com?a=&b=2`. To allow empty values, use `([^&]*)` instead of `([^&]+)`. – Kalinda Pride Mar 15 '22 at 18:48
22

Try using this:

[^&?]*?=[^&?]*
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Kent
  • 189,393
  • 32
  • 233
  • 301