Skip to content

Instantly share code, notes, and snippets.

@maximal
Last active September 23, 2015 06:58
Show Gist options
  • Save maximal/a6a40700d4ba37fb211a to your computer and use it in GitHub Desktop.
Save maximal/a6a40700d4ba37fb211a to your computer and use it in GitHub Desktop.
Сделать из строки HTTP-заголовков объект
/**
* Сделать из строки HTTP-заголовков объект.
*
* Такой текст:
* ```
* Date: Tue, 22 Sep 2015 17:26:15 GMT
* Content-Encoding: gzip
* Content-Type: text/plain; charset=utf-8
* Access-Control-Allow-Origin: *
* Connection: Keep-Alive
* Content-Length: 2054
* X-Pagination-Page-Next: https://sijeko.ru/?page=45
* ```
* превращается в объект:
* ```
* {
* date: 'Tue, 22 Sep 2015 17:26:15 GMT'
* contentEncoding: 'gzip',
* contentType: 'text/plain; charset=utf-8',
* accessControlAllowOrigin: '*',
* connection: 'Keep-Alive',
* contentLength: '2054',
* xPaginationPageNext: 'https://sijeko.ru/?page=45'
* }
* ```
*
*
* Пример использования:
* ```javascript
* jQuery.ajax({
* url: "https://sijeko.ru/temp/vlad-api/domic-pro.php",
* type: 'GET'
* }).done(function (data, textStatus, jqXHR) {
* console.log(
* jqXHR.getAllResponseHeaders(),
* getHeadersObject(jqXHR.getAllResponseHeaders())
* );
* });
* ```
*
* @param {String} headersString Строка с HTTP-заголовками.
* @returns Object HTTP-заголовки в форме объекта.
*
* @author MaximAL
* @since 2015-09-22 Первая версия
* @copyright © MaximAL, Sijeko 2015
* @link http://sijeko.ru
*/
function getHeadersObject(headersString) {
var res = {};
var headersArr = headersString.split('\n');
for (var i in headersArr) {
if (headersArr.hasOwnProperty(i)) {
var header = headersArr[i].split(': ', 2);
var headerKey = toCamelCase(header[0]);
if (headerKey !== '') {
res[toCamelCase(header[0])] = header[1];
}
}
}
return res;
/**
* Превратить строку в camelCase.
* Удобно, например, для создания полей объектов.
*
* @link http://stackoverflow.com/questions/2970525/converting-any-string-into-camel-case
*
* @param {String} str Строка, которую нужно превратить в camelCase
* @returns {String} Возвращает строку в форме camelCase
*
* @author MaximAL
* @since 2015-09-22 Первая версия
* @copyright © MaximAL, Sijeko 2015
* @link http://sijeko.ru
*/
function toCamelCase(str) {
return str
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); })
.replace(/[^a-zA-Z0-9]+/g, '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment