Before asking questions, look at examples...
Example 1) Matching non-global '?sort=alpha&direction=asc'
'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/);
Output:
// ['sort=alpha', 'sort', '=alpha', 'alpha']
Example 2) Matching global '?sort=alpha&direction=asc'
'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/g);
Output:
// ['sort=alpha', 'sort', '=alpha', 'alpha']
Example 3) Replacing with global match of '?sort=alpha&direction=asc'
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;
});
}
Output:
// sort=alpha sort =alpha alpha 1 ?sort=alpha&direction=asc
// direction=asc direction =asc asc 12 ?sort=alpha&direction=asc
My Curiosities
I might not have been able to figure this out alone, but I'm determined to understand the logic behind it. While I believe I grasp some concepts fully, there are always more to learn from those who know better!
- Are Examples 1) and 2) equivalent? If not, why?
- What does 'sort=alpha' signify in Examples 1) and 2)?
- Why doesn't Example 2) return both sort and direction parameters?
- What data is Example 3) iterating over with .replace()?
- Is there a way to capture N parameters without using .replace()?
Thank you!
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 conclusion, Example 3) remains correct, but for a more detailed explanation, refer to this answer.
End of Update
Special thanks to Steven Benner for the references: