Get the file name from a URL

Take the last path segment, ignoring the query and fragment.

JavaScript Version 1.0.0 · MIT · .md

get-the-file-name-from-a-url.js
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.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.