How to get file suffix name in javascript

  • 2021-08-06 19:55:34
  • OfStack

When uploading a file, it is often necessary to judge the type of the file, that is, the suffix name of the file, which can be easily achieved with javascript. Using Javascript to parse a file name with an absolute path and get a suffix, there are many methods, listed here for reference.

For a file name with an absolute path such as: D:\ Program Files\ Notepad + +\ Notepad + +. exe

First of all, to avoid the problem of escaping backslash, you can replace\ or\\ with # with regular expressions, such as:

D:#Program Files#Notepad++#Notepad++.exe

Then, with '#' as the separator, decompose the string into an array, and get the following array:

D: ProgramFiles Notepad++ Notepad++.exe

The last one in the array is the file name with suffix: Notepad + +. exe

Then, with '.' as the delimiter, decompose the suffix file name into an array, and get the following array:

Notepad++ exe

Then take the last one of the array to get the suffix exe of the file

The code is as follows (Win7+IE9 passed the test):


//by MoreWindows (http://blog.csdn.net/MoreWindows)
function GetExtensionFileName(pathfilename)
{
	var reg = /(\\+)/g;
	var pfn = pathfilename.replace(reg, "#");
	var arrpfn = pfn.split("#");
	var fn = arrpfn[arrpfn.length - 1];
	var arrfn = fn.split(".");
	return arrfn[arrfn.length - 1];
}

Test code:


function Test()
{
	var filePath="D:\\Program Files\\Notepad++\\Notepad++.exe";
	alert(GetExtensionFileName(filePath));
}
<input type="button" value="Test"  O nclick="Test()" />

Click the Test button to pop up the content of exe dialog, indicating that GetExtensionFileName can correctly resolve the file name with absolute path and get the suffix.

It is estimated that this method can only be used under Windows platform, but I don't know what will happen under Linux execution.


Related articles: