简体   繁体   中英

How can I get the value of the first and second line in a textarea?

I'm trying to get the value of the first and second line from a textarea in HTML.

The main problem is that the first and second line can be of different lengths, so I can't just copy X amount of characters.

Most of the solutions I've seen include JQuery, which I'm not familiar with, so I would prefer an answer that doesn't involve JQuery. However, if you do have an answer that does use JQuery, I'll also give it a go. Here's my code so far:

 textarea { resize: none; }
 <textarea id="c" placeholder="c" spellcheck="false"></textarea>

Assuming that the first and second line are separated by a newline (by pressing enter), you split it by "\\n" then get the second element.

function getSecondLine() {
    var tarea = document.getElementById("c")
    var tareavalue = tarea.value;
    var secondLine = tareavalue.split("\n")[1];
    console.log(secondLine)
}

 function getfirstAndsecondLine(inp) { var splittedInput = document.getElementById(inp).value.split('\\n'); var firstLine = splittedInput[0]; var secondLine = splittedInput[1]; console.log('first Line :' + firstLine); console.log(" "); console.log('second Line :' + secondLine); }
 <textarea id="c" placeholder="c" spellcheck="false"></textarea> <button onclick=getfirstAndsecondLine('c')> get first and second line </button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM