Neatest (and fast) way to remove top lines from a textarea

前端 未结 2 1548
情深已故
情深已故 2021-01-20 23:46

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

2条回答
  •  生来不讨喜
    2021-01-21 00:03

    Something like this (demo linked below is probably more useful):

    HTML

    
    

    Lines: 0

    JavaScript

    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/

提交回复
热议问题