Get the file name from a URL
Take the last path segment, ignoring the query and fragment.
function fileNameFromUrl(url) { const path = url.split(/[?#]/)[0]; return path.slice(path.lastIndexOf('/') + 1); }
Input & expected output
Input
"https://example.com/files/invoice-8812.pdf?download=1"Expected output
"invoice-8812.pdf"The edge case
Input
"https://example.com/files/"Expected output
""Know the limits
- The original kept the query string; this version drops ?… and #… first.
- Percent-encoding is not decoded.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Get the file name from a URL from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Drops the query string and fragment before taking the last segment. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Capitalize a string — Uppercase the first Unicode code point and preserve the remaining text.
- Reverse a string — Reverse Unicode code points without splitting surrogate pairs.
- Check a palindrome — Compare a string with its code-point reversal.