Diksha
Diksha

Reputation: 366

Split Function in Angular for a certain combination

I have a string which is like this:

  'Hello\r\nand World 15.6\n3'.

or it can be

  'Hello\r\nand World 15.6\nNA'.

and I want result which should split it like this:

  'Hello\r\nand World 15.6'
  '3'.

The code which I have written:

  var lines = string.split('\n');

which is producing result like this:

 'Hello\r'
 'and World 15.6'
 '3'.

What changes should I make in split() function to get the desired result?

Upvotes: 1

Views: 599

Answers (2)

acincognito
acincognito

Reputation: 1743

You can go with:

'Hello\r\nand World 15.6\n3'.split(/\n(?=\d)/);

Splits on every \n that is followed by a number.

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76717

You can replace \r\n with something else, then split by \n and put back the replaced \r\n:

'Hello\r\nand World 15.6\n3'.replaceAll('\r\n', '&newline').split('\n').map(item => item.replaceAll('&newline', '\\r\\n'))

Upvotes: 2

Related Questions