简体   繁体   中英

JS turn a multi-line string into an array (each item= a line)

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...

Use the split function:

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

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(' '));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM