# Get the file name from a URL

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

Canonical: https://1loc.dev/string/get-the-file-name-from-a-url/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function fileNameFromUrl(url) { const path = url.split(/[?#]/)[0]; return path.slice(path.lastIndexOf('/') + 1); }
```

## Input

```json
"https://example.com/files/invoice-8812.pdf?download=1"
```

## Expected output

```json
"invoice-8812.pdf"
```

## Edge case

Input:
```json
"https://example.com/files/"
```
Output:
```json
""
```

## Limits

- The original kept the query string; this version drops ?… and #… first.
- Percent-encoding is not decoded.

The lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/get-the-file-name-from-a-url.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Drops the query string and fragment before taking the last segment. Original MDX retained as inert source evidence.
