gpt4 book ai didi

Javascript - 仅从 textarea 中选择前 5 个非空行

转载 作者:行者123 更新时间:2023-11-30 15:51:21 25 4
gpt4 key购买 nike

在一个简单的 HTML 脚本中,我有两个元素:textarea 和一个无效的 Javascript 脚本(如下)。我的目标是只从文本区域中选择最多前 5 个非空行(每行由\n 分隔)。这段代码:

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

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


文本区域

<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('data').value;应该只保留这些行:

January
February
March
April
May

最佳答案

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>

关于Javascript - 仅从 textarea 中选择前 5 个非空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com