Home > Software design >  JS turn a multi-line string into an array (each item= a line)
JS turn a multi-line string into an array (each item= a line)

Time:12-05

For example, I have:

var str = "Hello
World"

I'm expecting an array like that : array["Hello", "World"]

I looked for a method that does that but nothing, I tried to make a loop but I don't know on what I should base my loop? From my knowledge there's not a .length property for the amount of lines in a string...

CodePudding user response:

Use the split function:

var str = `Hello
World`;
var splittedArray = str.split(/\r?\n/);
console.log(splittedArray)

CodePudding user response:

First thing is that the input string is not valid. It should be enclosed by backtick not with a quotes and then you can replace the new line break with the space and then split it to convert into an array.

Live Demo :

var str = `Hello
World`;

const replacedStr = str.replace(/\n/g, " ")

console.log(replacedStr.split(' '));

  • Related