-
-
Save joshsmith01/265df67ed64f4c5b981f04593f1a18de 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment