0

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

esqew
  • 42,425
  • 27
  • 92
  • 132
RedKitsun
  • 47
  • 3
  • Does this answer your question? [Split string in JavaScript and detect line break](https://stackoverflow.com/questions/21711768/split-string-in-javascript-and-detect-line-break) – esqew Dec 03 '22 at 13:21

2 Answers2

3

Use the split function:

var str = `Hello
World`;
var splittedArray = str.split(/\r?\n/);
console.log(splittedArray)
Konrad
  • 21,590
  • 4
  • 28
  • 64
MD Zand
  • 2,366
  • 3
  • 14
  • 25
  • This will throw a syntax error – Konrad Dec 03 '22 at 13:27
  • Put a semicolon at the end of line 2 – MD Zand Dec 03 '22 at 13:30
  • Still doesn't work. Semicolons are optional in javascript – Konrad Dec 03 '22 at 13:32
  • Hello! It works fine, a huge thanks! The only problem is that it takes tab character "\t" as part of the string in the array item. I'm trying to remove it by using the .replace("\t", "") property but it's working only once by item in the array, for example the string is a div with html tags in it and I want to keep the tags as text (I used .text for that) but to remove "\t". Any ideas about that man? You're a life saver – RedKitsun Dec 03 '22 at 13:34
  • @Konrad yeah I had an error at first but since the string I want to split is a div's content I don't have that syntax error, I guess this error comes from the fact that you can't manually just break to the line in JS code like that while declaring a variable. – RedKitsun Dec 03 '22 at 13:36
  • @Konrad check again – MD Zand Dec 03 '22 at 13:36
  • 2
    @RedKitsun `.replace(/\t/g, "")` – Konrad Dec 03 '22 at 13:37
-1

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(' '));
Debug Diva
  • 26,058
  • 13
  • 70
  • 123