gpt4 book ai didi

javascript - 如何将文本区域的最后三行添加到三个不同的变量?

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:12 24 4
gpt4 key购买 nike

我有一个带有 textarea 标签的 html 文件,我将在其中复制和粘贴一些多行文本,我想使用 javascript 在三个不同的变量中分别获取最后三行。textarea 被分配了一个 id="txt"。点击的函数被分配给 html 文件中的按钮。

function clicked(){
var txt = document.getElementById("txt");
var original = txt.value; //original text transfered to original variable

var lastline = //add last line in this variable

var secondlast = //add second last line in this variable

var thirdlast = //add third last line in this variable

var modified = //add text without these three lines in this variable


console.log(lastline); //how are you
console.log(secondlast); //now is the time
console.log(thirdlast); //helloo there
console.log(modified); //school data is the important
//checking home
//not there
}

textarea中输入的文字:

school data is the important
checking home
not there
helloo there
now is the time
how are you

输出:

how are you

now is the time

helloo there

school data is the important
checking home
not there

最佳答案

简单的功能:

function letsgo() {
var area= document.getElementById("mytext"),
//get all the lines in the textarea, seperated by \n or \r\n
lines = area.value.match(/[^\r\n]+/g),
//get bottom 3 lines, reverse them
bottom3 = lines.slice(-3).reverse();

var lastline=bottom3[0];
var secondlast=bottom3[1];
var thirdlast=bottom3[2];

//get all text except bottom 3 lines, joining them together with linefeed again
var rest = lines.slice(0, -3).join("\n");

//glue bottom3 and rest together
var result=bottom3.join("\n")+"\n"+rest;

//put in the textarea again
area.value=result;
}

关于javascript - 如何将文本区域的最后三行添加到三个不同的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48852349/

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