Skip to content

Instantly share code, notes, and snippets.

@mmazer
Created April 17, 2013 13:30
Show Gist options
  • Save mmazer/5404301 to your computer and use it in GitHub Desktop.
Save mmazer/5404301 to your computer and use it in GitHub Desktop.
JavaScript - parse XmlHttpRequest.getAllResponseHeaders into a key value pair.
/**
* XmlHttpRequest's getAllResponseHeaders() method returns a string of response
* headers according to the format described here:
* http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method
* This method parses that string into a user-friendly key/value pair object.
*/
function parseResponseHeaders(headerStr) {
var headers = {};
if (!headerStr) {
return headers;
}
var headerPairs = headerStr.split('\u000d\u000a');
for (var i = 0, len = headerPairs.length; i < len; i++) {
var headerPair = headerPairs[i];
var index = headerPair.indexOf('\u003a\u0020');
if (index > 0) {
var key = headerPair.substring(0, index);
var val = headerPair.substring(index + 2);
headers[key] = val;
}
}
return headers;
}
@tolemac
Copy link

tolemac commented Dec 9, 2016

Thanks!

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