0

I want to capture every name=value pair with regex in a url query.

Lets say I have queries like this:

?lm=1403085628
?lm=1403085628&other=343323
?lm=1403085628&other=&second=34342
?lm=1403085628&=343243&second=34342
?lm=1403085628&other=343323&some=efsfs
?
?lm=1403085628&other=343323&&&wrong

If I try this: ^\?(?:([a-zA-Z0-9-_]+\=[a-zA-Z0-9-_]+)&?)*

This capture the last occurrence only, for example some=efsfs for the third one.

But what I want is an array of key value pairs like this:

[
  'lm=1403085628', 
  'other=',
  'second=34342' 
]

How can I capture all occurrences of a capture group?

PS: I think this must have bee asked before but I cannot find any question, but maybe because I don't know the wording.

NoNameProvided
  • 8,608
  • 9
  • 40
  • 68
  • 1
    See [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Wiktor Stribiżew Feb 15 '17 at 12:28
  • Thanks, but thats doesn't answer my question, I need them as an array, the answer in the linked question assume I know the name of the parameters. – NoNameProvided Feb 15 '17 at 12:32
  • Is there only one answer? See https://jsfiddle.net/99k4szcn/, just wrote using that post. There may be better answers. – Wiktor Stribiżew Feb 15 '17 at 12:33
  • Possible duplicate of [How to get the value from the GET parameters?](http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters) – bharat Feb 15 '17 at 13:01

1 Answers1

1

How about

var regex = /(?:[?&](.*?)=([^?&]+))/g

regex.exec(inputQuery);

This would return values in this manner:

["?lm=1403085628", "lm", "1403085628"]

Index 0 is the match, index 1 is the name and index 2 is the value. If you do this in a loop you can capture both name and values right away

var result;
var values = [];
do {
  values.push(result);
} while(result = regex.exec(queryInput))

Alternatively (no regex, more efficient), you can just use:

'?lm=1403085628&other=&second=34342'.slice(1).split('&')
// Results in : ["lm=1403085628", "other=", "second=34342"]

EDIT: JsFiddle demonstrating the slice / split method

console.log('?lm=1403085628'.slice(1).split('&'));
console.log('?lm=1403085628&other=343323'.slice(1).split('&'));
console.log('?lm=1403085628&other=&second=34342'.slice(1).split('&'));
console.log('?lm=1403085628&=343243&second=34342'.slice(1).split('&'));
console.log('?lm=1403085628&other=343323&some=efsfs'.slice(1).split('&'));
console.log('?'.slice(1).split('&'));
console.log('?lm=1403085628&other=343323&&&wrong'.slice(1).split('&'));