TransWikia.com

How to get suffix of filename in javascript quickly?

Stack Overflow Asked by Daniel Stephens on December 13, 2020

This question has been asked a couple of times here on SO, but most answers are simply slow. I need the fastest implementation possible since I execute this on million filenames in a list.

filename.split(".").pop();

The code above works but imagine a long filename, isn’t there a way to start from the right? Otherwise, i could imagine that this here is faster than the common answers:

filename.reverse().split(".", 1).reverse()

2 Answers

Use lastIndexOf to iterate from the end of the string backwards to find the ., then slice the string:

const filename = 'foo/bar/baz/my-file.js';
const extension = filename.slice(filename.lastIndexOf('.') + 1);
console.log(extension);

Correct answer by CertainPerformance on December 13, 2020

You can also check that answer (and other answers in that question), it contains several methods with a benchmark: https://stackoverflow.com/a/12900504/4636502

Answered by MrCoconut on December 13, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP