How do you get a string separated by two new lines based on an index?

3129 views javascript
3

Let's say you have string:

Apple Banana Pear
Pineapple Grapefruit Kiwi
Lime Lemon Cherry

If I wanted the line

Pineapple Grapefruit Kiwi

how would I get this line from using any index of the second line and finding the newline before the index and the newline after the index?

I've tried doing this:

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

but it doesn't utilize the index but instead it just takes the second line. Sort of like a brute force solution to get the second line.

answered question

2 Answers

7

One option is to split the string by newlines and select the [1]st index - that is, the second line:

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

Or, if you don't want to create an intermediate array, you can match the substring that comes after one \n and before another \n:

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

posted this
10

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

Now list have all the lines which can be accessed through the index which ever line you want

posted this

Have an answer?

JD

Please login first before posting an answer.