Created
November 19, 2010 17:37
-
-
Save monsur/706839 to your computer and use it in GitHub Desktop.
Parses the response from XmlHttpRequest.getAllResponseHeaders() into a key/value pair.
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
/** | |
* 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; i < headerPairs.length; i++) { | |
var headerPair = headerPairs[i]; | |
// Can't use split() here because it does the wrong thing | |
// if the header value has the string ": " in it. | |
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; | |
} |
Here's my solution:
function getHeadersAsObject(xhr)
{
let headers = {}
xhr.getAllResponseHeaders()
.split('\u000d\u000a')
.forEach((line) => {
if (line.length > 0)
{
let delimiter = '\u003a\u0020',
header = line.split(delimiter)
headers[header.shift().toLowerCase()] = header.join(delimiter)
}
})
return headers
}
This work is dedicated to the public domain.
function parseResponseHeaders(headerStr) {
return Object.fromEntries(
(headerStr || '').split('\u000d\u000a') // '\n'
.map(line => line.split('\u003a\u0020')) // ": "
.filter(pair => pair[0] !== undefined && pair[1] !== undefined)
);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No license is always proper to use right? I don't really think Monsur would mind if you would use this :p