Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the filename from a URL in Elixir?

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?

like image 774
Gelo Chang Avatar asked Jan 25 '26 22:01

Gelo Chang


2 Answers

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"
like image 199
Dogbert Avatar answered Jan 28 '26 10:01

Dogbert


I think only need Path.basename/1:

"https://randomWebsite.com/folder/filename.jpeg"
|> Path.basename()
like image 27
hulin Avatar answered Jan 28 '26 12:01

hulin