What is the best way to extract a substring separated by two line breaks using a specific index?

Consider having the following string:

Apple Banana Pear
Pineapple Grapefruit Kiwi
Lime Lemon Cherry

If I am interested in extracting the line:

Pineapple Grapefruit Kiwi

how can I achieve this by identifying any index within the second line and locating the newline character before and after that index?

I attempted the following approach:

fruits[0].slice(fruits[0].indexOf("\n"),fruits[0]
                       .indexOf("\n", fruits[0].indexOf("\n") + 1))

However, this method does not take advantage of the index but merely extracts the entire second line. It resembles a brute force strategy to isolate the second line.

Answer №1

To extract the second line of a string, you can either split the string by newlines and select the 2nd index:

const fruits = `Apple Banana Pear
Pineapple Grapefruit Kiwi
Lime Lemon Cherry`;
const [,secondLine] = fruits.split('\n');
console.log(secondLine);

Alternatively, you can directly match the substring between two newline characters without creating an intermediate array:

const fruits = `Apple Banana Pear
Pineapple Grapefruit Kiwi
Lime Lemon Cherry`;
console.log(fruits.match(/\n([^\n]+)\n/)[1]);

Answer №2

One way to tackle this issue is by utilizing the split() function in a straightforward manner.

function extractLineFromString(text, lineNum) {
      let lines = text.split('\n');
      return lines[lineNum];
}

Answer №3

String fruits = "Apple Banana Pear   
Pineapple Grapefruit Kiwi
Lime Lemon Cherry";
List<String> fruitList = fruits.split("\n");
fruitList.get(1);

The 'fruitList' now contains all the individual lines of fruits which can be accessed through their respective indexes.

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

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

I am currently working on obtaining images that are saved by their URL within a PHP file. These images are located within a directory named "images."

My code is incomplete and not functioning as expected. $.get("museums.php",function(data,status){ var response=''; //console.log(data); var json = $.parseJSON(data); museums = json.museums; for(let m in museums) { $("#na ...

Three.js: It seems that THREE.WebGLRenderer detected the image is not a power of two, originally sized at 1600x900. It was resized to 102

As I dive into learning three.js, one of my goals is to incorporate a 16x9 photo into my scene. Below is the snippet of code where I add an Array of images to my scene: const material = new MeshBasicMaterial({ map: loader.load(images[i]), trans ...

creating a checkerboard using an array of JPanels

I am currently working on creating a chessboard by using an array of JPanels, where each box represents a JPanel with a specific color. However, I am encountering an issue when I try to make the assignment "chessboard[rows][columns] = b" as it results in a ...

Exploring collapsible data tables in Angular with Bootstrap styling

I am attempting to transform my static bootstrap data table, which displays the total count of fruits harvested in various months in an incremental manner, into a dynamic one using the JSON provided below: JSON { "fruit": [ { "fruitName": "Al ...

Leveraging IntersectionObserver to identify the video in view on the screen

Our Objective I aim to implement a swipe functionality for videos where the URL changes dynamically based on the ID of the currently displayed video. Challenges Faced Although I managed to achieve this with code, there is an issue where the screen flashe ...

NextJS configuration facing an issue with rewrite rules not functioning as intended

I have attempted to utilize a rewrite rule in the NextJS next.config.js file in order to redirect URLs containing '/lite' to '?amp=1', however, it does not seem to be functioning correctly in all scenarios. Below is the code from my ne ...

Exploring ways to repeatedly collapse rows using HTML, CSS, and JavaScript

GOAL: I want to freeze the header, freeze the first column, and be able to collapse rows multiple times. CURRENT PROGRESS: I have achieved freezing the header, first column, but can only collapse rows once. MY CODE SNIPPET: </head> <body> &l ...

What is the best way to style a tooltip in an ASP.NET application using CSS?

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { foreach (TableCell cell in e.Row.Cells) { ...

Positioning of Responsive Slider

I'm currently working on a responsive website, but I am facing challenges with the placement of the slideshow dots. When I switch to the device toolbar, they seem to change position. I have tried various methods such as using relative and absolute uni ...

What is the process of transforming an array of date strings into actual dates?

Looking for assistance in converting an array of date strings to actual Date objects. Here is the input data: medicalData = [ { name: 'Allergy', status: 'Normal', testDates: ['2023-07-02T13:21:29.643Z', '20 ...

Troubleshooting Vue.js data assignment issues

I'm attempting to implement basic form validation using Laravel 5.3 and Vue.js. Laravel controller: public function test(\Illuminate\Http\Request $request) { $this->validate($request, [ 'name' =&g ...

How to make a range slider using HTML

I am currently working with a range slider that displays only one value, but I want to show two limits - the minimum and maximum values. This is similar to a price range slider where users can select a range of prices. I need to store both the min and max ...

Is it possible to modify parameter values while transitioning?

While transitioning, I need the ability to modify parameter values. After researching the documentation, I discovered a method called `params('to')` that allows accessing target state's parameters. This is how it looks in my code: $transiti ...

Is there a way to define type information for a global variable when utilizing dynamic import within a function?

Here is a simplified version of my server code: server.ts import google from "googleapis"; const androidPublisher = google.androidpublisher("v3"); app.use('something', function(req, res, n){ ... }) ...(only one of the dozens of other meth ...

Determine the length of a C string

After explicitly stating the value of a string and comparing it to itself, the system returns FALSE. Could this be related to the additional '\0' character added by the system? How can I adjust my code to ensure a TRUE result? char name[5] ...

Unlocking numerical input solely by executing the specified command within the most up-to-date iteration of the Chrome Extension of Selenium IDE

After executing the command in Selenium IDE, I successfully extracted the sentence, "Your booking ID is 1234", and saved it in a variable named myText. <table> <tr> <th>Command</th> <th>Target</th> < ...

Highlight.js is not able to display HTML code

It's strange, I can't seem to get the HTML code to display correctly. This is my HTML: <head> <link rel="stylesheet" href="/path/to/default.css"> <script src="/path/to/highlight.pack.js"></script> <script& ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Exploring the ancestors of an element

JS <script> $('.btn').click(function(e){ target = e.target; parent = target.parentNode.parentNode; console.log(parent); }); </script> HTML <div class="card" sty ...