2

I have a series of varying strings which I need to turn into arrays on every second occurrence of \n, for simplicity please consider the next example:

const str = 'banana\napple\nmango\n3.5'

//I have tried and failed with:

const arr = str.split(/(^\n)+\n(^\n)+/)

// Result should be:
// const arr = ['banana\napple', 'mango\n3.5']

Do I have to use a loop here or what?

adiga
  • 34,372
  • 9
  • 61
  • 83
docHoliday
  • 241
  • 3
  • 15
  • Does this answer your question? [Cutting a string at nth occurrence of a character](https://stackoverflow.com/questions/5494691/cutting-a-string-at-nth-occurrence-of-a-character) – Mickael B. Jan 24 '20 at 11:59

2 Answers2

1

You could take match instead of split by taking some non breaking character, a breaking character and other non breking character.

const
    string = 'banana\napple\nmango\n3.5',
    result = string.match(/[^\n]+\n[^\n]+/g);
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Damn this is an ugly approach:

 
let t1 = performance.now();

const result = 'banana\napple\nmango\n3.5'
    .split('\n')
    .map((str, i, arr) => (i % 2) === 0 ? str + '\n' + arr[i+1] : null )
    .filter((str) => str !== null);
    
let t2 = performance.now();
console.log(result, t2-t1 + 'μs');
Seryoga
  • 793
  • 6
  • 15