Censor Characters between the first and last character of a string in elixir

212 views Asked by At

I want to replace/censor the characters of a username in elixir. So in the end, it should looks like in the bidders list in ebay: enter image description here

in elixir there is the String replace function, but i am a newbe at regex and i dont know what elixir-regex supports. so how can i achieve this?

iex> String.replace("username1234", someregex, "***")
"u***4"
1

There are 1 answers

2
Aleksei Matiushkin On BEST ANSWER

While you surely might accomplish this with regex “replace all but the first and the last symbols”

String.replace "username1234", ~r/(?<=\A.).*(?=.\z)/, "***"
#⇒ "u***4"

I’d better go with String.slice/3

first = String.slice("username1234", 0, 1)
last = String.slice("username1234", -1, 1)
"#{first}***#{last}"
#⇒ "u***4"

or String.graphemes/1

[h | t] = String.graphemes("username1234")
h <> "***" <> List.last(t)
#⇒ "u***4"