Skip to content

Instantly share code, notes, and snippets.

@joshsmith01
Forked from deiu/linkheaderparser.js
Created December 15, 2017 18:10
Show Gist options
  • Save joshsmith01/265df67ed64f4c5b981f04593f1a18de to your computer and use it in GitHub Desktop.
Save joshsmith01/265df67ed64f4c5b981f04593f1a18de to your computer and use it in GitHub Desktop.
Parse HTTP Link header in Javascript
// parse a Link header
//
// Link:<https://example.org/.meta>; rel=meta
//
// var r = parseLinkHeader(xhr.getResponseHeader('Link');
// r['meta'] outputs https://example.org/.meta
//
function parseLinkHeader(header) {
var linkexp = /<[^>]*>\s*(\s*;\s*[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g;
var paramexp = /[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g;
var matches = link.match(linkexp);
var rels = {};
for (var i = 0; i < matches.length; i++) {
var split = matches[i].split('>');
var href = split[0].substring(1);
var ps = split[1];
var s = ps.match(paramexp);
for (var j = 0; j < s.length; j++) {
var p = s[j];
var paramsplit = p.split('=');
var name = paramsplit[0];
var rel = paramsplit[1].replace(/["']/g, '');
rels[rel] = href;
}
}
return rels;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment