How to get file extension in JavaScript?

How to get file extension from a file name in JavaScript?

For examples,

For “file.txt”, I want to get “txt”.
For “file2.multi.ext.fileext”, I want to get “fileext”.

This JavaScript function works well for me.

function getExt(filename)
{
    var idx = filename.lastIndexOf('.');
    // handle cases like, .htaccess, filename
    return (idx < 1) ? "" : filename.substr(idx + 1);
}

It handles situations that the filename has no extensions like “.htaccess” and “filename”.


//This is fine if you know that there will be a nothing but a file name in "fileName" 
function getExt(fileName){
     return (fileName.lastIndexOf('.') < 1) ?   null : fileName.split('.').slice(-1);
}

//this is better for unexpected path data like: "/weird.folder/somefolder"
function getExt(path){
    return (path.match(/(?:.+..+[^\/]+$)/ig) != null) ? path.split('.').slice(-1): 'null';
}

Similar Posts

  • How to convert a ps file to a pdf file

    How to convert a ps file to a pdf file that is available for publish (embedded fonts, etc)? Convert the file.ps ps file to file.pdf: $ ps2pdf -dPDFSETTINGS=/printer file.ps file.pdf</pre> Embedding Fonts in PDFs with pdflatex by Jeffrey P. Bigham: http://www.manticmoo.com/articles/jeff/programming/latex/embedding-fonts-with-pdflatex.php Read more: How to merge multiple PDF files to a PDF on Linux? How…

  • Several Vim Tips (in Chinese)

    窗口模式操作 CTRL-W CTRL-S 将当前窗口分割为两窗口 CTRL-W CTRL-W 切换窗口 CTRL-W j 切换到下一窗口 CTRL-W k 切换到上一窗口 CTRL-W CTRL-R 将窗口的位置轮换 CTRL-W CTRL-_ 将当前窗口最小化 CTRL-W CTRL-= 将所有窗口变为等大 搜索和替换 /word 搜索word 搜索之后按回车高亮显示,n 下一个 p 上一个 :%s/模式/替换成的内容/gc % 全局选项,如果没有开启则只在当前行进行替换 g 表示 全局替换,如果没有g选项则只替换每行出现的第一个单词 c 表示需要确认 Esc替换按键 ESC键在键盘的左上角,按起来很不方便,而在VIM中ESC经常用到,其实有一个同样作用的组合按键:CTRL-[,这两个按起来手基本不用做大的动作,方便多了。 块操作 使用visual可视模式 v 进入可视模式,移动光标可进行选择 CTRL-Q 或 CTRL-V 进入列式模式,可进行块操作,选定的是一个矩形块。如果使用behave mswin CTRL-V可能映射成为past Read more: How to convert between…

  • How to write paper reviews?

    Sometimes, we need to write paper reviews after read many papers which belong to a specific area (like information retrieval). I have found some useful links which are as follows. http://www.uwlax.edu/biology/communication/ReviewPapers.htmlhttps://users.ece.utexas.edu/~miryung/teaching/EE382V-Fall2009/review.html Read more: How to convert A4 paper format to read on Kindle 5 How to resume a printing job on HP printer if the…

  • Get error message on usb2 stick – READ ONLY FILE SYSTEM. What should i do?

    Cant read or write to files on usb stick or move or copy them. Could you provide the dmesg output? It will help to understand your question. If it is formated on Windows, you may need to install the ntfs-3g package to write to the usb disk. Read more: mkfs refuses to make filesystem with…

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *