Sen said:
I'm using string.split(/^$/m, 2) on a curl output to separate header and
body. There’s an empty line between them. ^$ doesn’t seem to work...
First the caveat: not all UAs support the use of regular expressions as
arguments to split().
Now the problem: you haven't given any regular expression to match. The
'^' character means match the pattern when it occurs at the start of a
line, it does not match the start of a line itself. Similarly, $ does
not match the end of a line (which is different to how they are treated
in regular expressions in some other environments).
If you are looking for an empty line, then match the pattern that
represents two consecutive newlines. Where text is input to a browser
through a form control, in Firefox the required pattern is \n\n and in
IE it is \r\n\r\n. Other patterns may be needed for other browsers.
Since your text is generated elsewhere, you may need some other pattern.
You can match different patterns simultaneously using '|' (which means
or) between the patterns:
/\n\n|\r\n\r\n/
will match either \n\n or \r\n\r\n - i.e. a sequence of two consecutive
new lines in both Firefox and IE (presuming that there is absolutely
nothing on each line).
A safer pattern that allows for possible white space on the 'empty' line is:
/\n\s*\n|\r\n\s*\r\n/
Example curl output:
HTTP/1.1 404 Not Found
Date: Wed, 22 Feb 2006 00:01:45 GMT
Server: Apache/1.3.33 (Darwin) PHP/5.1.2 mod_perl/1.29
Transfer-Encoding: chunked
Content-Type: text/html; charset=iso-8859-1
That does not have any empty lines, how should head and body be
separated? Here is a small test case based on your sample text:
<form action="">
<textarea id="ta" rows="10" cols="60">HTTP/1.1 404 Not Found
Date: Wed, 22 Feb 2006 00:01:45 GMT
Server: Apache/1.3.33 (Darwin) PHP/5.1.2 mod_perl/1.29
Transfer-Encoding: chunked
Content-Type: text/html; charset=iso-8859-1</textarea>
<input type="button" value="Split header & body"
onclick="splitHB(this.form.ta.value);">
</form>
<script type="text/javascript">
function splitHB(txt)
{
var bits = txt.split(/\n\s*\n|\r\n\s*\r\n/);
alert('Header:\n' + bits[0]
+ '\n\nBody:\n' + bits[1]);
}
</script>
Shows an alert with:
Header:
HTTP/1.1 404 Not Found
Body:
Date: Wed, 22 Feb 2006 00:01:45 GMT
Server: Apache/1.3.33 (Darwin) PHP/5.1.2 mod_perl/1.29
Transfer-Encoding: chunked
Content-Type: text/html; charset=iso-8859-1
[...]