slice text in textbox after newline

Viewed 47

I have a textbox in reactjs. I want to slice its contents by new lines, outputting an array.

For example, if the textbox has

foo
bar
foobar

I want to get

['foo', 'bar', 'foobar']

Any ways I can do this?

3 Answers

\n means new line, I suggest trimming the text before splitting.

string.trim().split('\n')

UPDATE

as @Wyck suggest, if you need to remove the empty space around each line, you need to map each item and trim it.

string.trim().split('\n').map(s => s.trim())

We can use split() method here

let's consider an example
str = "x\ny";
console.log(str.split("\r\n"));


the output is ["x", "y"]

Related