Respuestas:
var filename = fullPath.replace(/^.*[\\\/]/, '')
Esto manejará las rutas \ OR / in
replacees mucho más lento que substr, lo que se puede usar junto con lastIndexOf('/')+1: jsperf.com/replace-vs-substring
"/var/drop/foo/boo/moo.js".replace(/^.*[\\\/]/, '')devolucionesmoo.js
Solo por el bien del rendimiento, probé todas las respuestas dadas aquí:
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
Y el ganador es la respuesta al estilo Split y Pop , ¡Gracias a bobince !
path.split(/.*[\/|\\]/)[1];
En Node.js, puede usar el módulo de análisis de Path ...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
basenamefunción:path.basename(file)
¿De qué plataforma proviene el camino? Las rutas de Windows son diferentes de las rutas POSIX son diferentes de las rutas de Mac OS 9 son diferentes de las rutas del sistema operativo RISC son diferentes ...
Si se trata de una aplicación web donde el nombre de archivo puede provenir de diferentes plataformas, no hay una solución única. Sin embargo, una puñalada razonable es usar '\' (Windows) y '/' (Linux / Unix / Mac y también una alternativa en Windows) como separadores de ruta. Aquí hay una versión que no es RegExp para mayor diversión:
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, su solución no protege contra una cadena vacía como entrada. En ese caso, falla con TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.
Bobince, aquí hay una versión de nickf que maneja delimitadores de ruta DOS, POSIX y HFS (y cadenas vacías):
return fullPath.replace(/^.*(\\|\/|\:)/, '');
No es más conciso que la respuesta de nickf , pero esta directamente "extrae" la respuesta en lugar de reemplazar las partes no deseadas con una cadena vacía:
var filename = /([^\\]+)$/.exec(fullPath)[1];
Una pregunta que pregunta "obtener nombre de archivo sin extensión" se refiere aquí, pero no hay solución para eso. Aquí está la solución modificada de la solución de Bobbie.
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
Otro
var filename = fullPath.split(/[\\\/]/).pop();
Aquí la división tiene una expresión regular con una clase de caracteres.
Los dos caracteres deben escaparse con '\'
O use la matriz para dividir
var filename = fullPath.split(['/','\\']).pop();
Sería la forma de empujar dinámicamente más separadores en una matriz, si es necesario.
Si fullPathse establece explícitamente por una cadena en su código, ¡debe escapar de la barra invertida !
Me gusta"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 respuesta completa es:
<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>
Pequeña función para incluir en su proyecto para determinar el nombre de archivo de una ruta completa para Windows, así como las rutas absolutas GNU / Linux y 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 exitoso para su pregunta, Prueba completa
<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)
}
Esta solución es mucho más simple y genérica, tanto para 'nombre de archivo' como para 'ruta'.
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(".") );
}