Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
@vogelsgesang

This comment has been minimized.

Show comment
Hide comment
@vogelsgesang

vogelsgesang Jul 10, 2014

Thank you very much for sharing this!
Just a small remark:
In lines 20 and 27 the variables i and j are not declared before they are used. Hence, they are leaked into the global scope.
I would write for (var i = 0; i < matches.length; i++) { (notice the var keyword)

vogelsgesang commented Jul 10, 2014

Thank you very much for sharing this!
Just a small remark:
In lines 20 and 27 the variables i and j are not declared before they are used. Hence, they are leaked into the global scope.
I would write for (var i = 0; i < matches.length; i++) { (notice the var keyword)

@deiu

This comment has been minimized.

Show comment
Hide comment
@deiu

deiu Sep 16, 2014

Thank you. I've fixed the example (albeit late).

Owner

deiu commented Sep 16, 2014

Thank you. I've fixed the example (albeit late).

@ukilon-okta

This comment has been minimized.

Show comment
Hide comment
@ukilon-okta

ukilon-okta Jan 2, 2015

What's the license for this gist?

ukilon-okta commented Jan 2, 2015

What's the license for this gist?

@deiu

This comment has been minimized.

Show comment
Hide comment
@deiu

deiu Aug 27, 2015

It's MIT.

Owner

deiu commented Aug 27, 2015

It's MIT.

@derekstavis

This comment has been minimized.

Show comment
Hide comment
@derekstavis

derekstavis Feb 20, 2016

A quick and tiny fix:

function parseLinkHeader(header)

shoud read

function parseLinkHeader(link)

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

derekstavis commented Feb 20, 2016

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