I have this code snippet aiming to extract next and last link values from github api...
var types = {},
str = '<https://api.github.com/repositories/1424470/issues?access_token=f554f90b4c95c78091a4202150d4583082dab1ce&page=2>; rel="next", <https://api.github.com/repositories/1424470/issues?access_token=f554f90b4c95c78091a4202150d4583082dab1ce&page=7>; rel="last"',
rex = /\s*<https?:\/\/api.github.com\/.+?&page=(\d+)>;\s*rel="(\w+?)"(?:,|$)/g;
// use regex replace method to capture multiple groups multiple times
str.replace(rex, function(_, page, type){
types[type] = +page;
});
console.log(types);
// {next: 2, last: 7}
It is functioning correctly, but feels like a mis-use of regex replace method, where I am not returning anything, but using it only for the sake of having a callback for each match, which I use to build up an output object.
I would prefer some kind of matchAll, returning multi-dimensional array of matches, and parts.
Is there a better way to handle this case in javascript?
regex.execmaintaining a starting index, allowing it to be called repeatedly, which is probably the most reasonable way to do it, but for such a general functionality, I would like to just pass a string and a pattern to a utility function, and be given back a multi-dimensional array of matches.