Skip to content

Instantly share code, notes, and snippets.

@niallo
Created July 14, 2012 04:54
Show Gist options
  • Save niallo/3109252 to your computer and use it in GitHub Desktop.
Save niallo/3109252 to your computer and use it in GitHub Desktop.
Parse Github `Links` header in JavaScript
/*
* parse_link_header()
*
* Parse the Github Link HTTP header used for pageination
* http://developer.github.com/v3/#pagination
*/
function parse_link_header(header) {
if (header.length == 0) {
throw new Error("input must not be of zero length");
}
// Split parts by comma
var parts = header.split(',');
var links = {};
// Parse each part into a named link
_.each(parts, function(p) {
var section = p.split(';');
if (section.length != 2) {
throw new Error("section could not be split on ';'");
}
var url = section[0].replace(/<(.*)>/, '$1').trim();
var name = section[1].replace(/rel="(.*)"/, '$1').trim();
links[name] = url;
});
return links;
}
@yurynix
Copy link

yurynix commented Apr 8, 2019

Handle the comma inside quotes with lookahead/lookbehind (only works on JS engines that support it)

function parseLinkHeader(header) {
    if (header.length === 0) {
        throw new Error("input must not be of zero length");
    }

    // Split parts by comma and parse each part into a named link
    return header.split(/(?!\B"[^"]*),(?![^"]*"\B)/).reduce((links, part) => {
        const section = part.split(/(?!\B"[^"]*);(?![^"]*"\B)/);
        if (section.length < 2) {
            throw new Error("section could not be split on ';'");
        }
        const url = section[0].replace(/<(.*)>/, '$1').trim();
        const name = section[1].replace(/rel="(.*)"/, '$1').trim();

        links[name] = url;

        return links;
    }, {});
}

@patarapolw
Copy link

patarapolw commented Aug 20, 2019

Can't it be as simple as?

function parseLink(s) {
  const output = {};
  const regex = /<([^>]+)>; rel="([^"]+)"/g;

  let m;
  while (m = regex.exec(s)) {
    const [_, v, k] = m;
    output[k] = v;
  }

  return output;
}

Usage: parseLink(headers.get("link"))

@DannyFeliz
Copy link

There is a package for this github-parse-link

@tillkruss
Copy link

Lodash:

const links = _.chain(link)
        .split(',')
        .map(link => {
          return {
            ref: link.split(';')[1].replace(/rel="(.*)"/, '$1').trim(),
            url: link.split(';')[0].replace(/<(.*)>/, '$1').trim(),
          }
        })
        .keyBy('ref')
        .mapValues('url')
        .value()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment