Examples first, questions second...
'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/);
// ['sort=alpha', 'sort', '=alpha', 'alpha']
'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/g);
// ['sort=alpha', 'sort', '=alpha', 'alpha']
getRequestParameters: function () {
var query_string = {},
regex = new RegExp('([^?=&]+)(=([^&]*))?', 'g');
'?sort=alpha&direction=asc'.replace(regex, function(match, p1, p2, p3, offset, string) {
console.log(match, p1, p2, p3, offset, string);
query_string[p1] = p3;
});
}
// sort=alpha sort =alpha alpha 1 ?sort=alpha&direction=asc
// direction=asc direction =asc asc 12 ?sort=alpha&direction=asc
I am not sure if I could have ever figured this one out on my own, but I never "live" with a solution and I must figure out the rhyme behind the reason. The specific matches I think understand "fully enough". I believe I know some of the answers below, but I rather not make assumptions and learn from smarter people!
Thanks!
update
var regex = new RegExp('([^?&=]+)(=([^&]*))?');
regex.exec('?sort=alpha&direction=asc');
// Chrome 21 - ["sort=alpha", "sort", "=alpha", "alpha"]
var regex = new RegExp('([^?&=]+)(=([^&]*))?', 'g');
regex.exec('?sort=alpha&direction=asc');
// Chrome 21 - ["sort=alpha", "sort", "=alpha", "alpha"]
'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/);
// Chrome 21 - ["sort=alpha", "sort", "=alpha", "alpha"]
'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/g);
// Chrome 21 - ["sort=alpha", "direction=asc"]
var regex = new RegExp('([^?&=]+)(=([^&]*))?', 'g');
regex.lastIndex = 11;
regex.exec('?sort=alpha&direction=asc');
// Chrome 21 - ["direction=asc", "direction", "=asc", "asc"]
In summary, Example 3) is still correct, but go to this answer for a more qualified response.
end update
References and thanks to Steven Benner:
Answers first, question afterwards:
["sort=alpha", "direction=asc"]
for the g
version - so they are not the same at all.match
is the entire matched string (in this case one or more characters that are not an ampersand, question mark or equal sign optionally followed by an equal sign and zero or more characters that are not an ampersand).replace
is iterating over each match it finds in the string.Use multiple calls to exec
or use the existing regex you have:
> '?sort=alpha&direction=asc&another=value'.match(/([^?&=]+)(=([^&]*))?/g);
["sort=alpha", "direction=asc", "another=value"]
What browser are you using that gave you the results you provided for your first questions?