javascript – Get values ​​from text

Question:

There is this text:

Date: Fri, 01 Apr 2016 03:21:49 GMT
Server: nginx
Content-Type: application/x-rar-compressed
Cache-Control: no-cache, private
Connection: keep-alive
Accept-Ranges: bytes
Keep-Alive: timeout=15
Content-Length: 63000000

or it could also be something like this:

Date: Fri, 01 Apr 2016 03:17:30 GMT
Last-Modified: Sat, 13 Dec 2014 08:28:52 GMT
Server: nginx
ETag: W/"548bf8c4-28496"
Vary: Accept-Encoding
Content-Type: image/jpeg
Connection: keep-alive
Content-Encoding: gzip

In general, you need to parse (if there is no text with a value, then a gap, as for example in the first example there is Content-Lenth: … , and in the second there is no) the following:
Content-Type: ….. (could be just something like application/exe , image/png , etc.)
Content-Length: ….. (can be any number)
How can I do that? given that one or both values ​​may be missing

Answer:

Why don't you break it down into an array of strings first?
And then parse each line, because your line has the form ключ : значение

/**
Date: Fri, 01 Apr 2016 03:21:49 GMT
Server: nginx
Content-Type: application/x-rar-compressed
Cache-Control: no-cache, private
Connection: keep-alive
Accept-Ranges: bytes
Keep-Alive: timeout=15
Content-Length: 63000000
*/

var txt; // текст выше
var lines = txt.split('\n'); // получаем строки
// теперь можем работать уже с каждой строкой
for(var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var props = line.split(':');
    var key = props[0]; // заголовок
    var value = props[1]; // значение заголовка
}
Scroll to Top