Я уверен, что кто-то может, и будет, минимизировать и / или оптимизировать мой код в будущем. Но с сейчас я на 200% уверен, что мой код работает в каждой уникальной ситуации (например, только с именем файла , с относительно , root-относительные и абсолютные URL-адреса, с фрагментом #
тегами, запросом ?
строк и всем остальным, что вы может решить бросить на это), безупречно, и с высокой точностью.
Для доказательства посетите: https://projects.jamesandersonjr.com/web/js_projects/get_file_extension_test.php
Вот JSFiddle: https://jsfiddle.net/JamesAndersonJr/ffcdd5z3/
Не для того, чтобы быть самонадеянным или дуть в мою трубу, но я не видел какого-либо блока кода для этой задачи (найти 'правильное' расширение файла, среди батарея различных function
входных аргументов), которая работает так же, как и эта.
Примечание: По умолчанию, если расширение файла не существует для данной входной строки, оно просто возвращает пустую строку ""
, ни ошибки, ни сообщения об ошибке.
Требуется два аргумента:
Строка: fileNameOrURL (не требует пояснений)
Boolean: showUnixDotFiles (Показывать или нет файлы, начинающиеся с точки ".")
Примечание (2): Если вам нравится мой код, обязательно добавьте его в свою библиотеку js и / или репозиторий, потому что я усердно работал над его совершенствованием, и было бы стыдно впустую. Итак, без лишних слов, вот оно:
function getFileExtension(fileNameOrURL, showUnixDotFiles)
{
/* First, let's declare some preliminary variables we'll need later on. */
var fileName;
var fileExt;
/* Now we'll create a hidden anchor ('a') element (Note: No need to append this element to the document). */
var hiddenLink = document.createElement('a');
/* Just for fun, we'll add a CSS attribute of [ style.display = "none" ]. Remember: You can never be too sure! */
hiddenLink.style.display = "none";
/* Set the 'href' attribute of the hidden link we just created, to the 'fileNameOrURL' argument received by this function. */
hiddenLink.setAttribute('href', fileNameOrURL);
/* Now, let's take advantage of the browser's built-in parser, to remove elements from the original 'fileNameOrURL' argument received by this function, without actually modifying our newly created hidden 'anchor' element.*/
fileNameOrURL = fileNameOrURL.replace(hiddenLink.protocol, ""); /* First, let's strip out the protocol, if there is one. */
fileNameOrURL = fileNameOrURL.replace(hiddenLink.hostname, ""); /* Now, we'll strip out the host-name (i.e. domain-name) if there is one. */
fileNameOrURL = fileNameOrURL.replace(":" + hiddenLink.port, ""); /* Now finally, we'll strip out the port number, if there is one (Kinda overkill though ;-)). */
/* Now, we're ready to finish processing the 'fileNameOrURL' variable by removing unnecessary parts, to isolate the file name. */
/* Operations for working with [relative, root-relative, and absolute] URL's ONLY [BEGIN] */
/* Break the possible URL at the [ '?' ] and take first part, to shave of the entire query string ( everything after the '?'), if it exist. */
fileNameOrURL = fileNameOrURL.split('?')[0];
/* Sometimes URL's don't have query's, but DO have a fragment [ # ](i.e 'reference anchor'), so we should also do the same for the fragment tag [ # ]. */
fileNameOrURL = fileNameOrURL.split('#')[0];
/* Now that we have just the URL 'ALONE', Let's remove everything to the last slash in URL, to isolate the file name. */
fileNameOrURL = fileNameOrURL.substr(1 + fileNameOrURL.lastIndexOf("/"));
/* Operations for working with [relative, root-relative, and absolute] URL's ONLY [END] */
/* Now, 'fileNameOrURL' should just be 'fileName' */
fileName = fileNameOrURL;
/* Now, we check if we should show UNIX dot-files, or not. This should be either 'true' or 'false'. */
if ( showUnixDotFiles == false )
{
/* If not ('false'), we should check if the filename starts with a period (indicating it's a UNIX dot-file). */
if ( fileName.startsWith(".") )
{
/* If so, we return a blank string to the function caller. Our job here, is done! */
return "";
};
};
/* Now, let's get everything after the period in the filename (i.e. the correct 'file extension'). */
fileExt = fileName.substr(1 + fileName.lastIndexOf("."));
/* Now that we've discovered the correct file extension, let's return it to the function caller. */
return fileExt;
};
Наслаждайтесь! Добро пожаловать!: