Risposte:
var filename = fullPath.replace(/^.*[\\\/]/, '')
Questo gestirà entrambi i percorsi \ OR / in
replaceè molto più lento di substr, che può essere utilizzato insieme a lastIndexOf('/')+1: jsperf.com/replace-vs-substring
"/var/drop/foo/boo/moo.js".replace(/^.*[\\\/]/, '')restituiscemoo.js
Solo per motivi di prestazioni, ho testato tutte le risposte fornite qui:
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
E il vincitore è la risposta in stile Split e Pop , grazie a bobince !
path.split(/.*[\/|\\]/)[1];
In Node.js è possibile utilizzare il modulo di analisi Path ...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
basenamefunzione:path.basename(file)
Da quale piattaforma proviene il percorso? I percorsi di Windows sono diversi dai percorsi POSIX sono diversi da quelli di Mac OS 9 sono diversi dai percorsi del sistema operativo RISC sono diversi ...
Se si tratta di un'app Web in cui il nome file può provenire da piattaforme diverse, non esiste una soluzione. Tuttavia, una pugnalata ragionevole è usare sia '\' (Windows) che '/' (Linux / Unix / Mac e anche un'alternativa su Windows) come separatori di percorsi. Ecco una versione non RegExp per un divertimento extra:
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);
Tuttavia, la tua soluzione non protegge da una stringa vuota come input. In tal caso, non riesceTypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties .
bobince, ecco una versione di nickf che gestisce i delimitatori di percorso DOS, POSIX e HFS (e stringhe vuote):
return fullPath.replace(/^.*(\\|\/|\:)/, '');
Non più conciso della risposta di Nickf , ma questo "estrae" direttamente la risposta invece di sostituire le parti indesiderate con una stringa vuota:
var filename = /([^\\]+)$/.exec(fullPath)[1];
Una domanda che chiede "ottieni il nome del file senza estensione" si riferisce qui, ma nessuna soluzione per questo. Ecco la soluzione modificata dalla soluzione di Bobbie.
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
Un altro
var filename = fullPath.split(/[\\\/]/).pop();
Qui split ha un'espressione regolare con una classe di caratteri
I due personaggi devono essere sfuggiti con '\'
Oppure usa l' array per dividere
var filename = fullPath.split(['/','\\']).pop();
Sarebbe il modo di spingere dinamicamente più separatori in un array, se necessario.
Se fullPathè esplicitamente impostato da una stringa nel tuo codice, è necessario evitare la barra rovesciata !
Piace"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>
La risposta completa è:
<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>
Poca funzione da includere nel progetto per determinare il nome file da un percorso completo per Windows, nonché percorsi assoluti GNU / Linux e 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>
Script riuscito per la tua domanda, Test completo
<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)
}
Questa soluzione è molto più semplice e generica, sia per "nome file" che per "percorso".
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(".") );
}