22

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?

3 Answers 3

35

You can use String.slice/2:

iex(1)> String.slice("Sergio", 1..-1)
"ergio"
iex(2)> String.slice("Sergio", 0..-3)                
"Serg"
2
  • Realize it's long after the fact but shouldn't that second expression be: String.slice("Sergio",0..3) (you've got -3 there). Nov 7, 2017 at 15:23
  • 2
    @OnorioCatenacci In this case -3 and 3 return the same thing. -3 counts from the back, 3 from the front.
    – Peter R
    Jun 1, 2018 at 3:45
5

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.
1
  • 1
    Your first method returns a charlist not a string. You'd want to add |> to_string() to the end. Oct 25, 2016 at 18:38
0

Besides String#slice there are also other ways to come up with the same result:

"Sergio" |> String.split(~r|(?<=\A.)|) |> List.last |> IO.inspect
#=> "ergio"
~r|(?<=\A.).*| |> Regex.run("Sergio") |> List.last |> IO.inspect
#=> "ergio"

In this particular case they bring no added value, but in some more complicated cases (as a reference to ruby's "Sergio"[/.../] they might have some sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.