There is such a 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 may 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 the pass, as for example in the first example there is a Content-Lenth: ..., and in the second there is no) the following:
Content-Type: ..... (maybe just something like application / exe, image / png, etc.)
Content-Length: ..... (can be any numbers)
How can I do that? considering that one or both values ​​may be missing

  • I did not understand something, what do you want to give to the input, and what do you want to get at the output? - Grundy
  • Enter 1 text or 2 at the input, and receive the Content-Length = .... and Content-Type = ..... (where the points are the sparse text there) - Madzal

2 answers 2

You can do the following:

 var 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'; var result = false; if( result = text.match( /Content-Length:\s*(\d+)/ )) { console.log(result[1]); } if( result = text.match( /Content-Type:\s*([^\s]+)/ )) { console.log(result[1]); } 

    Why don't you first break it up into an array of strings?
    And then each line is parsed, because you have a line of 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]; // значение заголовка }