In Ruby, I can go:
"Sergio"[1..-1] #> "ergio"
Doing the same in Elixir gives a runtime error:
iex(1)> "Sergio"[1..-1]
** (CompileError) iex:1: the Access syntax and calls to Access.get/2 are not available for the value: "Sergio"
Also tried:
iex(1)> String.slice("Sergio", 1, -1)
** (FunctionClauseError) no function clause matching in String.slice/3
(elixir) lib/string.ex:1471: String.slice("Sergio", 1, -1)
How can I get a substring from a string in Elixir?
You can use String.slice/2
:
iex(1)> String.slice("Sergio", 1..-1)
"ergio"
iex(2)> String.slice("Sergio", 0..-3)
"Serg"
If you want to get substring without first letter you can use also:
"Sergio" |> String.to_charlist() |> tl() |> to_string()
And another way to get substring from the end is:
a = "Sergio"
len = String.length(a)
String.slice(a, -len + 1, len - 1) # "ergio"
#this -len + 1 is -1(len - 1) and it's exact to Ruby's -1 when slicing string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With