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
  • 1,649
  • 6
  • 23
  • 59

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
  • 313,535
  • 40
  • 245
  • 254
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
  • 819
  • 6
  • 22