JavaScript를 사용하여 전체 경로에서 파일 이름을 얻는 방법은 무엇입니까?
전체 경로에서 마지막 값 ( '\'기호를 기준으로)을 얻을 수있는 방법이 있습니까?
예:
C:\Documents and Settings\img\recycled log.jpg
이 경우 recycled log.jpg
JavaScript의 전체 경로에서 벗어나고 싶습니다 .
var filename = fullPath.replace(/^.*[\\\/]/, '')
경로에서 \ OR /를 모두 처리합니다.
성능을 위해 여기에 주어진 모든 대답을 테스트했습니다.
var substringTest = function (str) {
return str.substring(str.lastIndexOf('/')+1);
}
var replaceTest = function (str) {
return str.replace(/^.*(\\|\/|\:)/, '');
}
var execTest = function (str) {
return /([^\\]+)$/.exec(str)[1];
}
var splitTest = function (str) {
return str.split('\\').pop().split('/').pop();
}
substringTest took 0.09508600000000023ms
replaceTest took 0.049203000000000004ms
execTest took 0.04859899999999939ms
splitTest took 0.02505500000000005ms
그리고 승자는 bobince 덕분에 Split and Pop 스타일 답변입니다 !
Node.js에서 Path의 파싱 모듈을 사용할 수 있습니다 ...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
경로는 어떤 플랫폼에서 제공됩니까? Windows 경로는 POSIX 경로와 다릅니다. Mac OS 9와 다릅니다. 경로는 RISC OS 경로와 다릅니다 ...
파일 이름이 다른 플랫폼에서 제공 될 수있는 웹 앱인 경우 솔루션이 없습니다. 그러나 합리적인 찌르기는 '\'(Windows) 및 '/'(Linux / Unix / Mac 및 Windows의 대안)을 경로 구분 기호로 사용하는 것입니다. 추가 재미를 위해 비 RegExp 버전이 있습니다.
var leafname= pathname.split('\\').pop().split('/').pop();
Ates에서 솔루션은 빈 문자열을 입력으로 보호하지 않습니다. 이 경우으로 실패합니다 TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties
.
bobince, DOS, POSIX 및 HFS 경로 구분 기호 (및 빈 문자열)를 처리하는 nickf 버전이 있습니다.
return fullPath.replace(/^.*(\\|\/|\:)/, '');
다음 JavaScript 코드 줄은 파일 이름을 제공합니다.
var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
nickf의 답변 보다 간결 하지는 않지만 원치 않는 부분을 빈 문자열로 바꾸는 대신 답변을 직접 "추출"합니다.
var filename = /([^\\]+)$/.exec(fullPath)[1];
"확장자없이 파일 이름 얻기"를 묻는 질문은 여기에 있지만 해결책은 없습니다. 다음은 Bobbie의 솔루션에서 수정 된 솔루션입니다.
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
나는 사용한다:
var lastPart = path.replace(/\\$/,'').split('\\').pop();
마지막을 대체 \
하므로 폴더와도 작동합니다.
다른 것
var filename = fullPath.split(/[\\\/]/).pop();
여기에 split 은 문자 클래스 가있는 정규 표현식
이 있습니다. 두 문자는 '\'로 이스케이프해야합니다.
그리고 이것은 하나의 배열로 나뉩니다 .
var filename = fullPath.split(['/','\\']).pop();
원하는 경우 구분 기호를 배열에 쉽게 넣을 수 있습니다!
프로그램에서 문자열을 코딩 하면 백 슬래시 를 이스케이프 처리 해야합니다 !
처럼"C:\\Documents and Settings\\img\\recycled log.jpg"
<script type="text/javascript">
function test()
{
var path = "C:/es/h221.txt";
var pos =path.lastIndexOf( path.charAt( path.indexOf(":")+1) );
alert("pos=" + pos );
var filename = path.substring( pos+1);
alert( filename );
}
</script>
<form name="InputForm"
action="page2.asp"
method="post">
<P><input type="button" name="b1" value="test file button"
onClick="test()">
</form>
완전한 대답은 다음과 같습니다.
<html>
<head>
<title>Testing File Upload Inputs</title>
<script type="text/javascript">
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'),with_this);
}
function showSrc() {
document.getElementById("myframe").href = document.getElementById("myfile").value;
var theexa = document.getElementById("myframe").href.replace("file:///","");
var path = document.getElementById("myframe").href.replace("file:///","");
var correctPath = replaceAll(path,"%20"," ");
alert(correctPath);
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file"
id="myfile"
onChange="javascript:showSrc();"
size="30">
<br>
<a href="#" id="myframe"></a>
</form>
</body>
</html>
GNU / Linux 및 UNIX 절대 경로뿐만 아니라 Windows의 전체 경로에서 파일 이름을 결정하기 위해 프로젝트에 포함 할 기능이 거의 없습니다.
/**
* @param {String} path Absolute path
* @return {String} File name
* @todo argument type checking during runtime
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
* @example basename('/home/johndoe/github/my-package/webpack.config.js') // "webpack.config.js"
* @example basename('C:\\Users\\johndoe\\github\\my-package\\webpack.config.js') // "webpack.config.js"
*/
function basename(path) {
let separator = '/'
const windowsSeparator = '\\'
if (path.includes(windowsSeparator)) {
separator = windowsSeparator
}
return path.slice(path.lastIndexOf(separator) + 1)
}
<html>
<head>
<title>Testing File Upload Inputs</title>
<script type="text/javascript">
<!--
function showSrc() {
document.getElementById("myframe").href = document.getElementById("myfile").value;
var theexa = document.getElementById("myframe").href.replace("file:///","");
alert(document.getElementById("myframe").href.replace("file:///",""));
}
// -->
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file"
id="myfile"
onChange="javascript:showSrc();"
size="30">
<br>
<a href="#" id="myframe"></a>
</form>
</body>
</html>
귀하의 질문에 대한 스크립트, 전체 테스트
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<p title="text" id="FileNameShow" ></p>
<input type="file"
id="myfile"
onchange="javascript:showSrc();"
size="30">
<script type="text/javascript">
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'), with_this);
}
function showSrc() {
document.getElementById("myframe").href = document.getElementById("myfile").value;
var theexa = document.getElementById("myframe").href.replace("file:///", "");
var path = document.getElementById("myframe").href.replace("file:///", "");
var correctPath = replaceAll(path, "%20", " ");
alert(correctPath);
var filename = correctPath.replace(/^.*[\\\/]/, '')
$("#FileNameShow").text(filename)
}
이 솔루션은 '파일 이름'과 '경로'모두에 대해 훨씬 간단하고 일반적입니다.
const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';
// regex to split path to two groups '(.*[\\\/])' for path and '(.*)' for file name
const regexPath = /^(.*[\\\/])(.*)$/;
// execute the match on the string str
const match = regexPath.exec(str);
if (match !== null) {
// we ignore the match[0] because it's the match for the hole path string
const filePath = match[1];
const fileName = match[2];
}
function getFileName(path, isExtension){
var fullFileName, fileNameWithoutExtension;
// replace \ to /
while( path.indexOf("\\") !== -1 ){
path = path.replace("\\", "/");
}
fullFileName = path.split("/").pop();
return (isExtension) ? fullFileName : fullFileName.slice( 0, fullFileName.lastIndexOf(".") );
}
var file_name = file_path.substring(file_path.lastIndexOf('/'));
'Programing' 카테고리의 다른 글
내부 클릭시 드롭 다운 메뉴 닫기를 피하십시오 (0) | 2020.03.25 |
---|---|
AngularJs : 파일 입력 필드의 변경 사항을 확인하는 방법은 무엇입니까? (0) | 2020.03.25 |
MySQL이 외래 키 제약 조건을 추가 할 수 없음 (0) | 2020.03.25 |
"x = x ++"다음에 x는 무엇입니까? (0) | 2020.03.25 |
Doctrine2 : 참조 테이블에 추가 열이있는 다대 다를 처리하는 가장 좋은 방법 (0) | 2020.03.25 |