Gelo Chang
Gelo Chang

Reputation: 125

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?

Upvotes: 3

Views: 2493

Answers (2)

hulin
hulin

Reputation: 161

I think only need Path.basename/1:

"https://randomWebsite.com/folder/filename.jpeg"
|> Path.basename()

Upvotes: 7

Dogbert
Dogbert

Reputation: 222318

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"

Upvotes: 8

Related Questions