A variant that works with all of the following inputs:
"file.name.with.dots.txt"
"file.txt"
"file"
""
null
undefined
would be:
var re = /(?:\.([^.]+))?$/;
var ext = re.exec("file.name.with.dots.txt")[1]; // "txt"
var ext = re.exec("file.txt")[1]; // "txt"
var ext = re.exec("file")[1]; // undefined
var ext = re.exec("")[1]; // undefined
var ext = re.exec(null)[1]; // undefined
var ext = re.exec(undefined)[1]; // undefined
Explanation
(?: # begin non-capturing group \. # a dot ( # begin capturing group (captures the actual extension) [^.]+ # anything except a dot, multiple times ) # end capturing group )? # end non-capturing group, make it optional $ # anchor to the end of the string