Skip to content

Instantly share code, notes, and snippets.

@deiu
Last active July 25, 2019 11:34
Show Gist options
  • Save deiu/9335803 to your computer and use it in GitHub Desktop.
Save deiu/9335803 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;
}
@deiu
Copy link
Author

deiu commented Aug 27, 2015

It's MIT.

@derekstavis
Copy link

A quick and tiny fix:

function parseLinkHeader(header)

shoud read

function parseLinkHeader(link)

Besides this it works like a charm! 🎉
Thanks for the Gist!

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