0

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?

7
  • @hwnd what are the options? Commented Aug 1, 2015 at 23:50
  • @hwnd that looks reasonable. A bit of a pain to have to write out the logic each time. Probably good case for utility function. Commented Aug 1, 2015 at 23:55
  • What do you mean write out the logic each time? Commented Aug 1, 2015 at 23:56
  • I mean the approach looks good. I had forgotten about regex.exec maintaining 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. Commented Aug 2, 2015 at 0:01
  • You can easily place that into a function. Commented Aug 2, 2015 at 0:02

1 Answer 1

1

You can use the exec() method in a loop, pushing the match results to a multi-dimensional array.

function find_all(re, s) {
   var types = [];
   while (m = re.exec(s)) {
        types.push([m[2], m[1]])
   }
   return types;
}

var regex = new RegExp('<https?://[^>]+page=(\\d+)>;\\s*rel="([^"]+)"', 'gi');

find_all(regex, str) //=> [ [ 'next', '2' ], [ 'last', '7' ] ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.