0

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()
Daniel Stephens
  • 2,371
  • 8
  • 34
  • 86

2 Answers2

3

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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

wjatek
  • 922
  • 7
  • 22