"What is the best way to store the last three lines of text from a textarea into three separate variables

I am working with an HTML file that contains a textarea tag. My goal is to copy and paste text with multiple lines into the textarea and then use JavaScript to extract the last three lines into three separate variables. The textarea has the id "txt" assigned to it. The function "clicked" is assigned to a button in the HTML file.

function clicked(){
    var txt = document.getElementById("txt");
    var original = txt.value; //original text transferred to original variable
    
    var lastline =  //store the last line in this variable
    
    var secondlast = //store the second to last line in this variable
    
    var thirdlast = //store the third to last line in this variable
    
    var modified = //store 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
  }
  

Text inputted in textarea:

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

Output:

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

Answer №1

Here is a straightforward function:

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

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

  //remove the bottom 3 lines from the text, join the rest together with linefeed
  var rest = lines.slice(0, -3).join("\n");

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

  //update the textarea with the rearranged text
  area.value=result;
}

Answer №2

When dealing with line breaks in a textarea, it's important to note that they are represented by line break characters and not HTML elements like <br>.

To extract individual lines from the textarea, you can normalize the line breaks to \n and then utilize the split() method on the textarea's value.

Below is a helpful utility function that executes a function for each line within a textarea's value:

function performActionOnEachLine(textarea, func) {
    var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
    var newLines, i;

    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 each line in an array
performActionOnEachLine(textarea, function(line) {
    lines.push(line);
});

Answer №3

This solution is very straightforward.

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);
}
<textarea id="txt"></textarea>
<button onclick="parse()">Parse</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for a way to make this HTML tab appear using ng-show and an external variable in AngularJS - seeking guidance as a beginner!

Here is the HTML code snippet controlling the tab presentation: <li class="presentation" ng-show="currentUserAuthority == LIBRARIAN" > However, there seems to be an issue with the variable "currentUserAuthority" not updating until after the web pag ...

In which location are HTML files stored within WordPress plugins?

Can someone help me locate the HTML files within WordPress plugins? I'm looking to make edits to the HTML and CSS files of a plugin, but I can't seem to find the specific HTML file. Any guidance on where these files are stored would be greatly ap ...

JSON data not displaying correctly in bootstrap table

I've been grappling with this issue for hours now, but I'm struggling to get my bootstrap table populated correctly. Here's the snippet of my HTML: <html> <head> <link rel="stylesheet" href="https://code.jquery.com/ui/1.1 ...

Exploring Relative Rotations in Three.js

I currently have a scenario where I have a THREE.Scene containing two meshes, namely meshA and meshB. Both of these meshes have been rotated differently. My objective is to take meshB out of the scene and attach it as a child of meshA, while maintaining it ...

Node.js population process

Hello, I am currently exploring Node.js and facing an issue with the populate() method. My goal is to populate the user model with forms. Here is the structure of the model: const UserSchema = new Schema({ firstName: { type: 'string&a ...

Unpacking Functions within Embedded Redux Reducer

My current challenge involves dispatching an action that has the following structure: { type: "TOGGLE_FARA", fara: true, id: "5d20d019cf42731c8f706db1" } The purpose of this action is to modify the "enabled" property within my "fara" state. The configura ...

I can't seem to figure out why my attempts to set a cookie through Express are failing

I am currently facing an issue with sending a cookie back to my React app after logging in. In my server, I have set up a test response: res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end(); In the app ...

Issue with background image positioning in IE 7 while scrolling

I am struggling with creating nested divs where the middle one has a fixed background image that remains static while the rest of the content scrolls. My solution works in Firefox, Chrome, and Opera but I'm encountering issues in IE7. Despite knowing ...

Dynamic Population of Django Drop Down List using JavaScript

In my Django + Python website, users can request access to a database through a form that provides them with the following options: Environment: A dropdown list with two values - Development and Production. Permission: Another dropdown list with two val ...

ASP.NET repeater causing jQuery scrollTop to malfunction after first use

I am facing a peculiar issue where I need to scroll through repeater items in a RadWindow using arrow keys in an ASP.NET application. Below is the code snippet: function isScrolledIntoView(elem) { var docViewTop; var docViewBottom ...

Creating text on a background image that does not adapt to different screen sizes is

How can I ensure that the text I write on an image stays within the image boundaries on small screen devices for full responsiveness? I've tried setting the image as the background of my div element, but the text overflows. Here is the code I used: ...

Instructions on how to save HTML "innerHTML" along with attributes to a text document

I'm currently developing an HTML export feature from a DIV tag that includes various elements and attributes. HTML: <div id="master"><span class="classname">content goes here</span></div> <span class="download" onclick="ca ...

adjust the dimensions of the clickable icon's background

Is there a way to expand the pressable area of a close icon without altering its size? For example, if the icon is 19X19 pixels, can the pressable area be increased to 39X39 pixels? The concern lies with the div element containing the close button and the ...

The scrolling feature in the option list for Adobe Air Client and Javascript appears to be non-functional

I am currently utilizing Air Client in conjunction with HTML, CSS and Javascript. My goal is to enable scrolling through the option list using the up and down arrow keys. However, I have encountered an issue where the scrollbar does not scroll all the way ...

Using JSON data to render images onto a canvas

I am encountering an issue with a JSON array that I'm receiving from PHP. The array is indexed and has the following format (larger in real scenario) [ [ [17, 28, 1, "z"], [28, 31, 6, "b"], [8, 29, 6, "b"] ...

Creating Secure JWT Tokens

Hello there! I'm currently in need of assistance with generating JWT tokens that include three headers: alg, kid, and typ. The format I am looking for is as follows: { "alg": "RS256", "kid": "vpaas-magic-cookie-1 ...

Trouble with CSS navigation

Hello! In Dreamweaver, I have completed the design for my navigation bar. Here is how it looks: However, when I view it in Firefox, the navigation appears all jumbled up. It's quite frustrating... Below is the code that I'm using: #navbar { ...

Blurring the background creates an "inset shadow" problem when transitioning

Problem: Strangely, when using Backdrop-filter: blur(Xpx); during a transition as shown below, unexpected "inset Shadows" mysteriously appear until the end of the transition. https://i.stack.imgur.com/uij7F.gif Illustration of the Issue Using jsfiddle Sp ...

What is the best way to capture dynamic import errors in JavaScript?

I am currently developing a website using Next.js. My goal is to utilize dynamic import import() to load a module dynamically, even if it may not exist. If the module does not exist, I am fine with suppressing it: const Blog = async () => { let L ...

"Although disabled, input elements can still be focused on in Firefox browser

Illustrative example let userInput = document.createElement("input"); userInput.id = "user-input"; userInput.type = "number"; userInput.className = "user-number-input"; userInput.disabled = true; document.body.appendChild(userInput); .number-inp ...