JavaScript로 파일 확장자를 얻으려면 어떻게해야합니까?
-
08-07-2019 - |
문제
코드 참조 :
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
해결책
최신 편집 : 이 질문이 처음 게시 된 이후 많은 것들이 바뀌 었습니다. 정말 좋은 정보가 많이 있습니다. Wallacer의 개정 된 답변 만큼 잘 비전의 훌륭한 고장
편집하다: 이것이 받아 들여진 답변이기 때문입니다. 왈레이서의 대답 실제로 훨씬 낫다 :
return filename.split('.').pop();
나의 오래된 대답 :
return /[^.]+$/.exec(filename);
해야합니다.
편집하다: Philho의 의견에 응답하여 다음과 같은 것을 사용하십시오.
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
다른 팁
return filename.split('.').pop();
간단하게 유지하십시오 :)
편집하다:
이것은 내가 더 효율적이라고 생각하는 또 다른 비 Regex 솔루션입니다.
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
더 잘 처리하는 코너 케이스가 있습니다. 비전의 대답 아래, 특히 확장이없는 파일 (.htaccess
등 포함).
매우 성능이 뛰어나고 코너 케이스를 반환하여 더 나은 방법으로 처리합니다. ""
도트 앞에 점이 없거나 문자열이 없을 때 전체 문자열 대신. 읽기가 어렵지만 매우 잘 제작 된 솔루션입니다. 당신의 도우미 lib에 넣고 그것을 사용하십시오.
오래된 편집 :
확장 기능이없는 파일을 실행하거나 확장이없는 파일을 사용하려는 경우 더 안전한 구현 (위의 Tom의 답변에 대한 Vision의 의견 참조).
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
return a.pop(); // feel free to tack .toLowerCase() here if you want
만약에 a.length
하나는 확장자가없는 가시적 파일입니다. 파일
만약에 a[0] === ""
그리고 a.length === 2
확장자가없는 숨겨진 파일입니다. .htaccess
이것이 약간 더 복잡한 경우 문제를 해결하는 데 도움이되기를 바랍니다. 성능면 에서이 솔루션은 Regex보다 조금 느립니다 대부분의 브라우저에서. 그러나 가장 일반적인 목적을 위해이 코드는 완벽하게 사용할 수 있어야합니다.
다음 솔루션은입니다 빠른 그리고 짧은 대량 작업에 사용하고 추가 바이트를 저장하기에 충분합니다.
return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
다음은 또 다른 한 줄의 비 레지스명 범용 솔루션입니다.
return fname.slice((Math.max(0, fname.lastIndexOf(".")) || Infinity) + 1);
둘 다 확장자가없는 이름으로 올바르게 작동합니다 (예 : 마이파일) 또는 시작 .
도트 (예 : .htaccess):
"" --> ""
"name" --> ""
"name.txt" --> "txt"
".htpasswd" --> ""
"name.with.many.dots.myext" --> "myext"
속도에 관심이 있으면 기준 제공된 솔루션이 가장 빠르지 만 짧은 솔루션은 엄청나게 빠릅니다.
짧은 작동 방식 :
String.lastIndexOf
메소드는 하위 문자열의 마지막 위치를 반환합니다 (예 :"."
) 주어진 문자열에서 (즉fname
). 기판을 찾을 수없는 경우 메소드가 반환됩니다-1
.- Filename에서 DOT의 "허용 할 수없는"위치는 다음과 같습니다.
-1
그리고0
, 확장이없는 이름을 각각 언급합니다 (예 :"name"
) 그리고 dot으로 시작하는 이름 (예 :".htaccess"
). - 제로 필 오른쪽 시프트 연산자 (
>>>
) 0으로 사용하면 음수 변환에 영향을 미칩니다-1
에게4294967295
그리고-2
에게4294967294
, 이는 Edge Case에서 변환되지 않은 필레나 이름을 유지하는 데 유용합니다 (여기서 속임수). String.prototype.slice
설명 된대로 계산 된 위치에서 파일 이름의 일부를 추출합니다. 위치 번호가 문자열 메서드의 길이보다 더 큰 경우""
.
동일한 방식으로 작동하는 더 명확한 솔루션을 원한다면 (전체 경로를 추가로 지원하여) 다음 확장 버전을 확인하십시오. 이 솔루션이 될 것입니다 느리게 이전 1 라이너보다 이해하기가 훨씬 쉽습니다.
function getExtension(path) {
var basename = path.split(/[\\/]/).pop(), // extract file name from full path ...
// (supports `\\` and `/` separators)
pos = basename.lastIndexOf("."); // get last position of `.`
if (basename === "" || pos < 1) // if file name is empty or ...
return ""; // `.` not found (-1) or comes first (0)
return basename.slice(pos + 1); // extract extension ignoring `.`
}
console.log( getExtension("/path/to/file.ext") );
// >> "ext"
세 가지 변형은 모두 클라이언트 측의 모든 웹 브라우저에서 작동하며 서버 측 Nodejs 코드에서도 사용할 수 있습니다.
function getFileExtension(filename)
{
var ext = /^.+\.([^.]+)$/.exec(filename);
return ext == null ? "" : ext[1];
}
테스트
"a.b" (=> "b")
"a" (=> "")
".hidden" (=> "")
"" (=> "")
null (=> "")
또한
"a.b.c.d" (=> "d")
".a.b" (=> "b")
"a..b" (=> "b")
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}
var extension = fileName.substring(fileName.lastIndexOf('.')+1);
var parts = filename.split('.');
return parts[parts.length-1];
function file_get_ext(filename)
{
return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
}
암호
/**
* Extract file extension from URL.
* @param {String} url
* @returns {String} File extension or empty string if no extension is present.
*/
var getFileExtension = function (url) {
"use strict";
if (url === null) {
return "";
}
var index = url.lastIndexOf("/");
if (index !== -1) {
url = url.substring(index + 1); // Keep path without its segments
}
index = url.indexOf("?");
if (index !== -1) {
url = url.substring(0, index); // Remove query
}
index = url.indexOf("#");
if (index !== -1) {
url = url.substring(0, index); // Remove fragment
}
index = url.lastIndexOf(".");
return index !== -1
? url.substring(index + 1) // Only keep file extension
: ""; // No extension found
};
테스트
쿼리가 없으면 조각이 여전히 존재할 수 있습니다.
"https://www.example.com:8080/segment1/segment2/page.html?foo=bar#fragment" --> "html"
"https://www.example.com:8080/segment1/segment2/page.html#fragment" --> "html"
"https://www.example.com:8080/segment1/segment2/.htaccess?foo=bar#fragment" --> "htaccess"
"https://www.example.com:8080/segment1/segment2/page?foo=bar#fragment" --> ""
"https://www.example.com:8080/segment1/segment2/?foo=bar#fragment" --> ""
"" --> ""
null --> ""
"a.b.c.d" --> "d"
".a.b" --> "b"
".a.b." --> ""
"a...b" --> "b"
"..." --> ""
jslint
0 경고.
빠르고 경로에서 올바르게 작동합니다
(filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
일부 가장자리 케이스
/path/.htaccess => null
/dir.with.dot/file => null
분할을 사용하는 솔루션은 느리고 LastIndexof의 솔루션은 에지 케이스를 처리하지 않습니다.
이 시도:
function getFileExtension(filename) {
var fileinput = document.getElementById(filename);
if (!fileinput)
return "";
var filename = fileinput.value;
if (filename.length == 0)
return "";
var dot = filename.lastIndexOf(".");
if (dot == -1)
return "";
var extension = filename.substr(dot, filename.length);
return extension;
}
나는 이것을 공유하고 싶었다.
fileName.slice(fileName.lastIndexOf('.'))
이에는 몰락이 있지만 확장자가없는 파일은 마지막 문자열을 반환합니다. 그러나 그렇게한다면 이것은 모든 것을 고칠 것입니다.
function getExtention(fileName){
var i = fileName.lastIndexOf('.');
if(i === -1 ) return false;
return fileName.slice(i)
}
// 获取文件后缀名
function getFileExtension(file) {
var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i;
var extension = file.match(regexp);
return extension && extension[1];
}
console.log(getFileExtension("https://www.example.com:8080/path/name/foo"));
console.log(getFileExtension("https://www.example.com:8080/path/name/foo.BAR"));
console.log(getFileExtension("https://www.example.com:8080/path/name/.quz/foo.bar?key=value#fragment"));
console.log(getFileExtension("https://www.example.com:8080/path/name/.quz.bar?key=value#fragment"));
return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");
편집 : 이상하게도 (또는 아마도 그렇지 않을 수도 있습니다) $1
교체 방법의 두 번째 인수에서는 작동하지 않는 것 같습니다 ... 죄송합니다.
Tom의 답변이 문제를 분명히 해결하지만 P4BL0의 답변에 대해 의견을 제시하는 것만으로는 충분하지 않다는 것을 깨달았습니다.
return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
대부분의 응용 프로그램의 경우 : 간단한 스크립트와 같은 간단한 스크립트입니다
return /[^.]+$/.exec(filename);
톰이 제공 한대로 잘 작동합니다. 그러나 이것은 바보 증거가 아닙니다. 다음 파일 이름이 제공되는 경우 작동하지 않습니다.
image.jpg?foo=bar
약간 과잉 일 수 있지만 다음과 같은 URL 파서를 사용하는 것이 좋습니다. 이 하나 예측할 수없는 파일 이름으로 인한 실패를 피합니다.
해당 특정 기능을 사용하면 다음과 같은 파일 이름을 얻을 수 있습니다.
var trueFileName = parse_url('image.jpg?foo=bar').file;
URL vars없이 "image.jpg"를 출력합니다. 그런 다음 파일 확장자를 자유롭게 가져올 수 있습니다.
function func() {
var val = document.frm.filename.value;
var arr = val.split(".");
alert(arr[arr.length - 1]);
var arr1 = val.split("\\");
alert(arr1[arr1.length - 2]);
if (arr[1] == "gif" || arr[1] == "bmp" || arr[1] == "jpeg") {
alert("this is an image file ");
} else {
alert("this is not an image file");
}
}
function extension(fname) {
var pos = fname.lastIndexOf(".");
var strlen = fname.length;
if (pos != -1 && strlen != pos + 1) {
var ext = fname.split(".");
var len = ext.length;
var extension = ext[len - 1].toLowerCase();
} else {
extension = "No extension found";
}
return extension;
}
//용법
Extension ( 'file.jpeg')
확장자 하위 CAS를 항상 반환하여 필드 변경 작업에서 확인할 수 있습니다.
file.jpeg
파일 (확장 없음)
파일. (noextension)
특정 확장을 찾고 길이를 알고 있다면 사용할 수 있습니다. 기판:
var file1 = "50.xsl";
if (file1.substr(-4) == '.xsl') {
// do something
}
자바 스크립트 참조 : https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/string/substr
나는 파티에 늦었지만 단순함을 위해 나는 이런 식으로 사용합니다.
var fileName = "I.Am.FileName.docx";
var nameLen = fileName.length;
var lastDotPos = fileName.lastIndexOf(".");
var fileNameSub = false;
if(lastDotPos === -1)
{
fileNameSub = false;
}
else
{
//Remove +1 if you want the "." left too
fileNameSub = fileName.substr(lastDotPos + 1, nameLen);
}
document.getElementById("showInMe").innerHTML = fileNameSub;
<div id="showInMe"></div>
쿼리 매개 변수와 URL의 모든 문자를 설명하는 원한 솔루션.
string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()
// Example
// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
// jpg
이 간단한 솔루션
function extension(filename) {
var r = /.+\.(.+)$/.exec(filename);
return r ? r[1] : null;
}
테스트
/* tests */
test('cat.gif', 'gif');
test('main.c', 'c');
test('file.with.multiple.dots.zip', 'zip');
test('.htaccess', null);
test('noextension.', null);
test('noextension', null);
test('', null);
// test utility function
function test(input, expect) {
var result = extension(input);
if (result === expect)
console.log(result, input);
else
console.error(result, input);
}
function extension(filename) {
var r = /.+\.(.+)$/.exec(filename);
return r ? r[1] : null;
}
나는 누군가가 내 코드를 미래에 할 수 있고, 최소화하고,/또는 최적화 할 수 있다고 확신합니다. 그러나 현재 지금 바로, 나는 200%가 내 코드가 모든 고유 한 상황에서 작동한다고 확신합니다 (예 : 파일 이름 만, 와 함께 상대적인, 루트-관계, 그리고 순수한 URL과 함께 파편 #
태그와 함께 질문 ?
현악기, 그리고 당신이 그것을 던지기로 결정할 수있는 모든 것), 완벽하게, 그리고 핀 포인트 정밀도.
증거를 위해 방문 : https://projects.jamesandersonjr.com/web/js_projects/get_file_extension_test.php
JSFiddle은 다음과 같습니다. https://jsfiddle.net/jamesandersonjr/ffcdd5z3/
과도하게 자신감이 없거나 내 트럼펫을 불고 있지만 나는 보지 못했습니다. 어느 이 작업을위한 코드 블록 (찾기 '옳은' 다른 배터리 가운데서 파일 확장 function
입력 인수)는 이것과 마찬가지로 작동합니다.
메모: Design에 의해, 주어진 입력 문자열에 파일 확장자가 존재하지 않으면 단순히 빈 문자열을 반환합니다. ""
, 오류 나 오류 메시지가 아닙니다.
두 가지 논쟁이 필요합니다.
끈: filenameorurl (자기 설명)
부울 : showUnixDotFiles (점으로 시작하는 파일을 표시하든 없든 ".")
노트 2): 내 코드가 마음에 들면 JS 라이브러리 및/또는 repo에 추가하십시오. 제가 완성하기 위해 열심히 노력했기 때문에 낭비하는 것은 부끄러운 일입니다. 따라서 더 이상 고민하지 않고 여기에 있습니다.
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;
};
즐기다! 당신은 정말 환영합니다! :
Wallacer의 대답은 좋지만 한 가지 더 확인이 필요합니다.
파일에 확장자가 없으면 파일 이름을 확장자로 사용합니다.
이거 한번 해봐:
return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';
일부 파일은 확장 기능이 없을 수 있다는 것을 잊지 마십시오.
var parts = filename.split('.');
return (parts.length > 1) ? parts.pop() : '';
var file = "hello.txt";
var ext = (function(file, lio) {
return lio === -1 ? undefined : file.substring(lio+1);
})(file, file.lastIndexOf("."));
// hello.txt -> txt
// hello.dolly.txt -> txt
// hello -> undefined
// .hello -> hello
웹 URL을 처리하는 경우 다음을 사용할 수 있습니다.
function getExt(filename){
return filename.split('.').pop().split("?")[0].split("#")[0];
}
getExt("logic.v2.min.js") // js
getExt("http://example.net/site/page.php?id=16548") // php
getExt("http://example.net/site/page.html#welcome") // html
fetchFileExtention(fileName) {
return fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
}
이에 대한 표준 라이브러리 기능이 있습니다. path
기준 치수:
import path from 'path';
console.log(path.extname('abc.txt'));
산출:
.txt
따라서 형식 만 원한다면 다음과 같습니다.
path.extname('abc.txt').slice(1) // 'txt'
확장자가 없으면 함수는 빈 문자열을 반환합니다.
path.extname('abc') // ''
그렇다면 노드를 사용하는 경우 path
내장되어 있습니다. 브라우저를 목표로하는 경우 Webpack은 path
당신을위한 구현. 웹 팩없이 브라우저를 타겟팅하는 경우 Path-Browserify 수동으로.
문자열 분할 또는 정규를 수행 할 이유가 없습니다.
var filetypeArray = (file.type).split("/");
var filetype = filetypeArray[1];
이것은 더 나은 접근 방식 IMO입니다.