Trim all newlines from String in Kotlin - idiomatic way

Viewed 34

Is there a built-in/standard lib method to trim all new lines from a string, not only from the beginning or the end?

1 Answers

There is no special stdlib function to my knowledge that specifically removes new lines, but you could simply use text.replace("\n", "") if you're only interested in removing \n characters.

If you want to cover more cases, like more line ending characters/sequences, or whitespace after new lines, you can also use a regex. For instance text.replace(Regex("""(\r\n)|\n"""), ""), but that may be overkill in many cases.

Yet another option is to get the lines themselves independently, and then join them back together with an empty separator:

text.lines().joinToString("")
Related