Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

std/url/basename.ts>basename

Deno standard library
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
function basename
import { basename } from "https://deno.land/std@0.209.0/url/basename.ts";

Return the last portion of a URL, or the host name if there is no path. Trailing /s are ignored, and optional suffix is removed.

Examples

Example 1

import { basename } from "https://deno.land/std@0.209.0/url/basename.ts";

// basename accepts a string or URL
console.log(basename("https://deno.land/std/assert/mod.ts"));  // "mod.ts"
console.log(basename(new URL("https://deno.land/std/assert/mod.ts"))); // "mod.ts"

// basename accepts an optional suffix to remove
console.log(basename(new URL("https://deno.land/std/assert/mod.ts"), ".ts")); // "mod"

// basename does not include query parameters or hash fragments
console.log(basename(new URL("https://deno.land/std/assert/mod.ts?a=b"))); // "mod.ts"
console.log(basename(new URL("https://deno.land/std/assert/mod.ts#header"))); // "mod.ts"

// If no path is present, the host name is returned
console.log(basename(new URL("https://deno.land/"))); // "deno.land"

Parameters

url: string | URL
  • url to extract the final path segment from.
optional
suffix: string
  • optional suffix to remove from extracted name.

Returns

string

the last portion of the URL path, or the URL origin if there is no path.