DEV Community

Discussion on: Put Down the Destructuring Hammer

Collapse
 
aiosifelisl1 profile image
Andreas Iosifelis • Edited

I love how we can get the extension of a file name like so:

const [, extension] = filename.split('.')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sleavely profile image
Joakim Hedlund

I get the feeling this approach won't work well with files such as foo.bar.js. You may want to reverse() after splitting and picking the first entry as extension instead.

Collapse
 
merri profile image
Vesa Piittinen • Edited
const filename = 'filename.test.js';
const extension = filename.split('.').pop();
Enter fullscreen mode Exit fullscreen mode

Or if you must have destructure:

const [extension] = /[^.]+$/.exec(filename) ?? [];
Enter fullscreen mode Exit fullscreen mode

But whichever solution that actually is able to select the very last part will work.