views:

3243

answers:

4

I am trying to parse url-encoded strings that are made up of key=value pairs separated by either & or &.

The following will only match the first occurrence, breaking apart the keys and values into separate result elements:

var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/)

The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be:

['1111342', 'Adam%20Franco']

Using the global flag, 'g', will match all occurrences, but only return the fully matched sub-strings, not the separated keys and values:

var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/g)

The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be:

['1111342=Adam%20Franco', '&348572=Bob%20Jones']

While I could split the string on & and break apart each key/value pair individually, is there any way using JavaScript's regular expression support to match multiple occurrences of the pattern /(?:&|&)?([^=]+)=([^&]+)/ similar to PHP's preg_match_all() function?

I'm aiming for some way to get results with the sub-matches separated like:

[['1111342', '348572'], ['Adam%20Franco', 'Bob%20Jones']]

or

[['1111342', 'Adam%20Franco'], ['348572', 'Bob%20Jones']]
+2  A: 

Set the g modifier for a global match:

/…/g
Gumbo
+3  A: 

You need to use the 'g' switch for a global search

var result = mystring.match(/(&|&)?([^=]+)=([^&]+)/g)
meouw
+7  A: 

I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually:

var url = "http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr";
var re  = /(?:\?|&(?:amp;)?)([^=]+)=?([^&]*)?/g;
var match;
while (match = re.exec(url)) {
  alert(match[1] + " = " + match[2]);
}

Outputs:

f = q
source = s_q
hl = de
geocode = undefined
q = Frankfurt+am+Main
sll = 50.106047,8.679886
sspn = 0.370369,0.833588
ie = UTF8
ll = 50.116616,8.680573
spn = 0.35972,0.833588
z = 11
iwloc = addr
Tomalak
This is what I was hoping for. What I've never seen in JavaScript documentation is mention that the exec() method will continue to return the next result set if called more than once. Thanks again for the great tip!
Adam Franco
It does because of this: http://www.regular-expressions.info/javascript.html (Read through: "How to Use The JavaScript RegExp Object")
Tomalak
there is a bug in this code: the semicolon after the "while" should be removed.
Jan Willem B
@Jan: Sharp eyes, you are right! Fixed, thanks for the hint.
Tomalak
+1  A: 

Great!!

Thanks for sharing the code.