Odpowiedzi:
var filename = fullPath.replace(/^.*[\\\/]/, '')
To obsłuży obie ścieżki \ OR /
replacejest znacznie wolniejsze niż substr, co można stosować w połączeniu z lastIndexOf('/')+1: jsperf.com/replace-vs-substring
"/var/drop/foo/boo/moo.js".replace(/^.*[\\\/]/, '')powrotymoo.js
Ze względu na wydajność przetestowałem wszystkie podane tutaj odpowiedzi:
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
Zwycięzcą jest odpowiedź w stylu split i pop , dzięki bobince !
path.split(/.*[\/|\\]/)[1];
W Node.js możesz użyć modułu parsującego Path ...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
basenamefunkcji:path.basename(file)
Z jakiej platformy pochodzi ścieżka? Ścieżki systemu Windows różnią się od ścieżek POSIX różnią się od ścieżek Mac OS 9 ścieżki różnią się od ścieżek RISC OS są różne ...
Jeśli jest to aplikacja internetowa, w której nazwa pliku może pochodzić z różnych platform, nie ma jednego rozwiązania. Jednak rozsądnym rozwiązaniem jest użycie zarówno „\” (Windows), jak i „/” (Linux / Unix / Mac, a także alternatywy w Windows) jako separatorów ścieżek. Oto wersja bez RegExp dla dodatkowej zabawy:
var leafname= pathname.split('\\').pop().split('/').pop();
var path = '\\Dir2\\Sub1\\SubSub1'; //path = '/Dir2/Sub1/SubSub1'; path = path.split('\\').length > 1 ? path.split('\\').slice(0, -1).join('\\') : path; path = path.split('/').length > 1 ? path.split('/').slice(0, -1).join('/') : path; console.log(path);
Ates, twoje rozwiązanie nie chroni przed pustym łańcuchem jako wejściem. W takim przypadku kończy się niepowodzeniem TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.
bobince, oto wersja nickf, która obsługuje ograniczniki DOS, POSIX i HFS (i puste ciągi znaków):
return fullPath.replace(/^.*(\\|\/|\:)/, '');
Nie bardziej zwięzłe niż odpowiedź nickf , ale ta bezpośrednio „wyodrębnia” odpowiedź zamiast zastępować niechciane części pustym ciągiem:
var filename = /([^\\]+)$/.exec(fullPath)[1];
Pytanie „pobierz nazwę pliku bez rozszerzenia” znajduje się tutaj, ale nie ma na to rozwiązania. Oto rozwiązanie zmodyfikowane z rozwiązania Bobbiego.
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
Inny
var filename = fullPath.split(/[\\\/]/).pop();
Tutaj split ma wyrażenie regularne z klasą znaków
znaków Dwa znaki muszą być poprzedzone znakiem \
Lub użyj tablicy do podzielenia
var filename = fullPath.split(['/','\\']).pop();
W razie potrzeby byłby to sposób dynamicznego wypychania większej liczby separatorów do tablicy.
Jeśli fullPathjest to jawnie ustawione przez ciąg znaków w kodzie, musisz uciec od ukośnika odwrotnego !
Lubić"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>
Pełna odpowiedź to:
<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>
Niewiele funkcji do uwzględnienia w projekcie w celu określenia nazwy pliku z pełnej ścieżki dla Windows, a także bezwzględnych ścieżek GNU / Linux i UNIX.
/**
* @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>
Skopiuj pomyślnie swoje pytanie, pełny test
<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)
}
To rozwiązanie jest znacznie prostsze i ogólne, zarówno dla „nazwy pliku”, jak i „ścieżki”.
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(".") );
}