Javascript - 只选择textarea中的前5个非空行

时间:2016-09-01 20:31:48

标签: javascript html

在一个简单的HTML脚本中,我有两个元素:textarea和一个不起作用的Javascript脚本(如下)。我的目标是只从textarea中选择UP TO前5个非空行(每行由\ n分割)。这段代码:

var textarea = document.getElementbyId(' data')。value;

从textarea中选择所有(10)行,但我只想选择最多5行并忽略其余行。我把我的工作尝试放在这里 - http://jsfiddle.net/1xst7e22/

TEXTAREA

<textarea id="data" style="width:100%;height:300px">
January
February

March
April
May
June
July
August
September
October
November
December
</textarea>

JAVASCRIPT (这是我悲惨的尝试,没有工作......):假设x = 5:

function getLines (x)
{
var textarea = document.getElementbyId('data');
var firstX = (textarea.value ? textarea.value + "\n" : "");

      if (firstX.length > x) firstX = firstX.slice(x);

      textarea.value = firstX.join("\n");
}

-

因此,当脚本正常工作时,textarea = document.getElementbyId(&#39; data&#39;)。value;应该只持有以下几行:

January
February
March
April
May

2 个答案:

答案 0 :(得分:1)

试试这段代码:

   function getLines(x) { 
        var textarea = document.getElementById('data'); 
        var firstX = textarea.innerHTML.split("\n").slice(0,x).join("\n")
        textarea.value = firstX;
    }

答案 1 :(得分:1)

var data = document.getElementById('data');
var dataArray = data.value.split("\n");
dataArray = dataArray.slice(0,5);
data.value = dataArray.join("\n");
<textarea id="data" style="width:100%;height:300px">
January
February
March
April
May
June
July
August
September
October
November
December
</textarea>