Javascript의 파일 이름 문자열에서 확장자를 추출하는 방법은 무엇입니까?
변수에 있는 파일의 파일 확장자를 얻으려면 어떻게 해야 합니까?예를 들어 파일이 1.txt일 경우 txt 부분이 필요합니다.
다음 입력과 함께 작동하는 변형입니다.
"file.name.with.dots.txt""file.txt""file"""nullundefined
다음과 같습니다.
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
설명.
(?: # 비실행 그룹 시작\. # 점( # 그룹 캡처를 시작합니다(실제 내선번호 표시)[^].+ # 점을 제외한 모든 것, 여러 번) # 캡처 그룹 종료)? # 비호환 그룹 종료, 옵션 설정$ # 문자열 끝에 고정
저는 개인적으로 끈을 나눠서.마지막 어레이 요소를 반환하기만 하면 됩니다.
var fileExt = filename.split('.').pop();
없는 경우.파일명을 지정하면 문자열 전체가 반환됩니다.
예:
'some_value' => 'some_value'
'.htaccess' => 'htaccess'
'../images/something.cool.jpg' => 'jpg'
'http://www.w3schools.com/jsref/jsref_pop.asp' => 'asp'
'http://stackoverflow.com/questions/680929' => 'com/questions/680929'
를 사용합니다.lastIndexOfmethod를 사용하여 문자열의 마지막 마침표를 찾고 그 뒤에 문자열 부분을 가져옵니다.
var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
indexOf()가 아닌 lastIndexOf()를 사용하는 것이 좋습니다.
var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))
다음을 사용하는 것이 좋습니다.항상 기능합니다!
var ext = fileName.split('.').pop();
그러면 닷 프리픽스 없이 내선번호가 반환됩니다.". + 확장자를 추가하여 지원하는 확장자와 대조할 수 있습니다.
var x = "1.txt";
alert (x.substring(x.indexOf(".")+1));
주 1: 파일 이름이 file.filename 형식일 경우 이 기능은 작동하지 않습니다.txt
주 2: 파일 이름이 폼 파일일 경우 실패합니다.
이거 먹어봐.문제를 해결할 수 있습니다.
var file_name_string = "file.name.string.png"
var file_name_array = file_name_string.split(".");
var file_extension = file_name_array[file_name_array.length - 1];
안부 전해요
아래 코드를 사용합니다.
var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
}
return fileExt;
파일 이름에 더 많은 . (dots)가 있는 경우 해결 방법입니다.
<script type="text/javascript">var x = "file1.asdf.txt";
var y = x.split(".");
alert(y[(y.length)-1]);</script>
변수 값을 가져온 다음 확장자를 다음과 같이 구분합니다.
var find_file_ext=document.getElementById('filename').value;
var file_ext=/[^.]+$/.exec(find_file_ext);
이게 도움이 될 거야
언급URL : https://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript
'source' 카테고리의 다른 글
| python 목록 결합 (0) | 2022.12.12 |
|---|---|
| 배열에 대한 라라벨 컬렉션 (0) | 2022.12.12 |
| 한 목록에서 발생하는 모든 요소를 다른 목록에서 제거합니다. (0) | 2022.12.12 |
| POST 파라미터를 Postman으로 송신하는 것은 동작하지 않지만 GET 파라미터를 송신하는 것은 동작합니다. (0) | 2022.12.12 |
| AngularJs ng-repeat 핸들 빈 목록 대소문자 (0) | 2022.12.12 |