var file1 = "50.xsl"; var file2 = "30.doc"; getFileExtension(file1); //returs xsl getFileExtension(file2); //returs doc function getFileExtension(filename) { /*TODO*/ }
function getFileExtension1(filename) { return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename)[0] : undefined; }
split
methodfunction getFileExtension2(filename) { return filename.split('.').pop(); }
slice
, lastIndexOf
methodsfunction getFileExtension3(filename) { return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2); } console.log(getFileExtension3('')); // '' console.log(getFileExtension3('filename')); // '' console.log(getFileExtension3('filename.txt')); // 'txt' console.log(getFileExtension3('.hiddenfile')); // '' console.log(getFileExtension3('filename.with.many.dots.ext')); // 'ext'
'.'
in this case). Returns -1
if the value is not found.lastIndexOf
for parameter 'filename'
and '.hiddenfile'
are -1
and 0
respectively. Zero-fill right shift operator (»>) will transform -1
to 4294967295
and -2
to 4294967294
, here is one trick to insure the filename unchanged in those edge cases.""
.Solution | Paramters | Results |
---|---|---|
Solution 1: Regular Expression | ’‘ ‘filename’ ‘filename.txt’ ‘.hiddenfile’ ‘filename.with.many.dots.ext’ | undefined undefined ‘txt’ ‘hiddenfile’ ‘ext’ |
Solution 2: String split | ’‘ ‘filename’ ‘filename.txt’ ‘.hiddenfile’ ‘filename.with.many.dots.ext’ | ’’ ‘filename’ ‘txt’ ‘hiddenfile’ ‘ext’ |
Solution 3: String slice , lastIndexOf | ’‘ ‘filename’ ‘filename.txt’ ‘.hiddenfile’ ‘filename.with.many.dots.ext’ | ’’ ‘’ ‘txt’ ‘’ ‘ext’ |