Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace consecutive whitespace with a single space from the whole string

Tags:

elixir

I have a string with 2,3 or more spaces between non-space characters

string = "a  b c   d"

What can I do to make it like that:

output_string == "a b c d"
like image 900
asiniy Avatar asked Sep 08 '16 14:09

asiniy


2 Answers

The simplest way would be using Regular Expressions:

iex(1)> string = "a  b c   d"
"a  b c   d"
iex(2)> String.replace(string, ~r/ +/, " ") # replace only consecutive space characters
"a b c d"
iex(3)> String.replace(string, ~r/\s+/, " ") # replace any consecutive whitespace
"a b c d"
like image 142
Dogbert Avatar answered Sep 29 '22 14:09

Dogbert


For what it's worth, you don't even need the regex:

iex(3)> "a b c    d" |> String.split |> Enum.join(" ")
#=>"a b c d"

Also just from my very little bit of smoke testing, it looks like this will work with any whitespace separators (i. e. it works on spaces and tabs as far as I can tell).

like image 22
Onorio Catenacci Avatar answered Sep 29 '22 15:09

Onorio Catenacci