我有一个带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
答案 0 :(得分:1)
简单的功能:
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;
}
答案 1 :(得分:0)
textarea的value
内的换行符用换行符而不是HTML <br>
元素表示。]
您可以通过将换行符规范化为\n
然后在textarea的值上调用split()
方法来获取各行。
这是一个实用程序函数,它为textarea值的每一行调用一个函数:
function actOnEachLine(textarea, func) {
var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
var newLines, i;
// Use the map() method of Array where available
if (typeof lines.map != "undefined") {
newLines = lines.map(func);
} else {
newLines = [];
i = lines.length;
while (i--) {
newLines[i] = func(lines[i]);
}
}
textarea.value = newLines.join("\r\n");
}
var textarea = document.getElementById("txt");
var lines; // Store your lines in an array
actOnEachLine(textarea, function(line) {
lines.push(line) //
});
答案 2 :(得分:0)
这很简单。
var lastline,secondlast,thirdlast,modified;
function parse()
{
var elem = document.getElementById("txt");
var text = elem.value;
var arr = text.replace(/\n/g,"$").split("$");
if(arr.length) lastline = arr.pop();
if(arr.length) secondlast = arr.pop();
if(arr.length) thirdlast = arr.pop();
modified = arr.join("\n");
console.log(lastline,secondlast,thirdlast);
console.log(modified);
}
&#13;
<textarea id="txt"></textarea>
<button onclick="parse()">Parse</button>
&#13;