Last active
July 25, 2019 11:34
-
-
Save deiu/9335803 to your computer and use it in GitHub Desktop.
Parse HTTP Link header in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
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
It's MIT.