I have a webpage that displays last 1000
lines of a logfile then updates via AJAX every x
seconds loading new content (if any) and appending to textare
Something like this (demo linked below is probably more useful):
Lines: 0
var $log = $('#log'),
$button = $('#clickme'),
$numLines = $('#numLines'),
MAX_LINES = 5000,
lorem_ipsum = ' Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
lineCounter = 0;
$button.click(function()
{
$log.val($log.val() + generateMoreLines()).change();
});
$log.change(function ()
{
var text = tail(MAX_LINES, $log.val());
$log.val(text);
$numLines.text(countNewlines(text));
});
function generateMoreLines()
{
var buf = [];
for (var i = 0; i < 1000; i++)
{
buf.push(lineCounter++ + lorem_ipsum);
}
return buf.join('\n');
}
function countNewlines(haystack)
{
return count('\n', haystack);
}
function count(needle, haystack)
{
var num = 0,
len = haystack.length;
for (var i=0; i < len; i++)
{
if (haystack.charAt(i) === needle)
{
num++;
}
}
return num;
}
function tail(limit, haystack)
{
var lines = countNewlines(haystack) + 1;
if (lines > limit)
{
return haystack
.split('\n')
.slice(-limit)
.join('\n');
}
return haystack;
}
The newline handling isn't perfect (do you count all occurrences of '\n'
? What if the string starts or ends with '\n'
? etc.).
Demo: http://jsfiddle.net/mattball/3ghjm/