Here's my problem I want to get the file name from the URL ex. https://randomWebsite.com/folder/filename.jpeg
I got the expected result on javascript using this string.substring(string.lastIndexOf('/')+1)
. In Elixir I use this function String.slice(string, <first_value_from_binary.match>..String.length(string)
... :binary.match()
only gets the first index of the first char that match the given letter... or is there any other solution getting the file name from the URL than this?
Asked
Active
Viewed 1,619 times
3

Adam Millerchip
- 20,844
- 5
- 51
- 74

Gelo Chang
- 127
- 8
-
1In [tag:elixir] there are **no arrays**, we have lists instead, and, hence, no indexes. `"https://randomWebsite.com/folder/filename.jpeg" |> String.split("/") |> List.last()` – Aleksei Matiushkin Mar 29 '21 at 10:03
2 Answers
8
You can parse the string into a URI
using URI.parse/1
, get its :path
, and call Path.basename/1
to get the name of the last segment of the path:
iex(1)> "https://randomWebsite.com/folder/filename.jpeg" |> URI.parse() |> Map.fetch!(:path) |> Path.basename()
"filename.jpeg"

Dogbert
- 212,659
- 41
- 396
- 397
-
Cool Thanks. I have a question what is the difference if I just do ```"https://randomWebsite.com/folder/filename.jpeg" |> Path.basename()``` it outputs the same value – Gelo Chang Mar 30 '21 at 03:20
-
1Looking at the source code of the functions, I think `Path.basename/1` would be fine for your use case. – Dogbert Mar 31 '21 at 10:44
7
I think only need Path.basename/1
:
"https://randomWebsite.com/folder/filename.jpeg"
|> Path.basename()

hulin
- 151
- 3
-
Interestingly `Path` says it is for use with "filesystem paths", but it uses [Erlang's `filename`](http://erlang.org/doc/man/filename.html#basename-1) module internally, which has a much wider scope: "With filename is meant all strings that can be used to denote a file." – Adam Millerchip Mar 29 '21 at 20:59
-