PHP's basename in TypeScript

✓ Verified: PHP 8.3
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { basename } from 'locutus/php/filesystem/basename'.

Or with CommonJS: const { basename } = require('locutus/php/filesystem/basename')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1basename('/www/site/home.htm', '.htm')'home'
2basename('ecra.php?p=1')'ecra.php?p=1'
3basename('/some/path/')'path'
4basename('/some/path_ext.ext/','.ext')'path_ext'

Here's what our current TypeScript equivalent to PHP's basename looks like.

export function basename(path: string, suffix?: string): string {
// discuss at: https://locutus.io/php/basename/
// parity verified: PHP 8.3
// original by: Kevin van Zonneveld (https://kvz.io)
// improved by: Ash Searle (https://hexmen.com/blog/)
// improved by: Lincoln Ramsay
// improved by: djmix
// improved by: Dmitry Gorelenkov
// example 1: basename('/www/site/home.htm', '.htm')
// returns 1: 'home'
// example 2: basename('ecra.php?p=1')
// returns 2: 'ecra.php?p=1'
// example 3: basename('/some/path/')
// returns 3: 'path'
// example 4: basename('/some/path_ext.ext/','.ext')
// returns 4: 'path_ext'

let b = path
if (b.endsWith('/') || b.endsWith('\\')) {
b = b.slice(0, -1)
}

b = b.replace(/^.*[/\\]/g, '')

if (typeof suffix === 'string' && b.endsWith(suffix)) {
b = b.slice(0, -suffix.length)
}

return b
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP filesystem functions


Star