0

I have a string with multiple lines.

one
two
three

I need to add them to an array separated by line

How can I do that?

2 Answers2

1

You can use string.split to cut your string at newlines. You can add a Array.filter to remove the empty lines.

Filter will loop at every string and create a new array. If the string is empty it will not push it to the new array.

const str = `one
two

three`;

const ret = str.split('\n').filter(x => x.length);

console.log(str);
console.log(ret);
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
0

You can use String.prototype.split() such as below

const someString = `one
two
three`;

const myArray = someString.split('\n');

console.log(myArray);
Mihir Kale
  • 1,028
  • 1
  • 12
  • 20