How do I split a string by each line break?

I’m pretty sure I did the following:

local str = "Hello \n World"
prints(str:split("\n"))

This outputted:

{
[1] = "Hello ", --> Notice the space at the end
[2] = " World" --> Notice the space at the beginning
}

(I think) This let me know that the string wasn’t being split by each line break, but by the actual string phrase “\n”

If I’m incorrect, please let me know. If you do know how to split a string by a line break, that would be great!

1 Like

"\n" is a line break. What you’re describing is removing the space next to the line break. Normally when using a line break you’re expected to not add spaces around it e.g. "Hello\nWorld".

If you want to remove whitespace around a line break you can include "%s*" on both sides of the matching pattern.

local str = "Hello \n World"
print(string.split(str, "%s*\n%s*"))
2 Likes