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

空扰寡人 提交于 2019-12-01 22:28:04

You should be able to use a single split and then join after truncating the data, something like this:

// on data retrieved
var total = ((textarea.value 
              ? textarea.value + "\n" 
              : "") 
          + new_data).split("\n");

if (total.length > 10) 
    total = total.slice(total.length - 10);

textarea.value = total.join("\n");

Working example: http://jsfiddle.net/ArvQ7/ (cut to 10 lines for brevity)

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

HTML

<button id="clickme">More lines</button>
<br/>
<textarea id="log" rows="24" cols="80"></textarea>
<p>Lines: <span id="numLines">0</span></p>

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!