How to remove the new line characters from a string?
12,612
Solution 1
What's wrong with this?
String.strip
only supports removing one character. That error is thrown as Elixir tries to convert "\r\n"
to a single character (source):
iex(1)> s = "\r\n"
"\r\n"
iex(2)> <<s::utf8>>
** (ArgumentError) argument error
Moreover, String.strip
has been deprecated in favor of String.trim
, which does support a string as the second argument, but that function will only remove the exact sequence \r\n
from the starting and ending of the string:
iex(1)> aaa = """
...(1)> fdsfds fdsfds
...(1)> fdsfdsfds
...(1)> fdsfdsfds
...(1)> """
"fdsfds fdsfds\n fdsfdsfds\nfdsfdsfds\n"
iex(2)> String.trim(aaa, "\r\n")
"fdsfds fdsfds\n fdsfdsfds\nfdsfdsfds\n"
iex(3)> String.trim(aaa, "\r\n") == aaa
true
which I doubt is what you want as you said "I want to remove all the symbol of a new line". To remove all \r
and \n
, you can use String.replace
twice:
iex(4)> aaa |> String.replace("\r", "") |> String.replace("\n", "")
"fdsfds fdsfds fdsfdsfdsfdsfdsfds"
Solution 2
Escape the newlines
"""
fdsfds fdsfds \
fdsfdsfds \
fdsfdsfds
"""
Author by
Meji
Updated on July 23, 2022Comments
-
Meji almost 2 years
I want to remove all the newline symbols:
aaa = """ fdsfds fdsfds fdsfdsfds fdsfdsfds """ |> String.strip("\r\n")
And I get:
argument error
What's wrong with this?
-
Aleksei Matiushkin over 7 years
aaa |> String.replace(~r/\r|\n/, "")
? -
Dogbert over 7 years@mudasobwa I personally wouldn't use a Regex for such simple cases, but that's certainly a valid solution! I also think in this case my 2 String replace solution would be faster than your Regex one although I haven't measured it.
-
Francisco Quintero over 3 yearsThanks for the
String.trim
tip about the exact sequence. -
Mario Uher over 2 yearsThis should be the accepted answer imho.