Câu trả lời:
var filename = fullPath.replace(/^.*[\\\/]/, '')
Điều này sẽ xử lý cả \ OR / trong đường dẫn
replacelà nhiều chậm hơn so với substr, có thể được sử dụng kết hợp với lastIndexOf('/')+1: jsperf.com/replace-vs-substring
"/var/drop/foo/boo/moo.js".replace(/^.*[\\\/]/, '')trả vềmoo.js
Chỉ vì mục đích thực hiện, tôi đã thử nghiệm tất cả các câu trả lời được đưa ra ở đây:
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
Và người chiến thắng là câu trả lời theo phong cách Split và Pop , Cảm ơn bobince !
path.split(/.*[\/|\\]/)[1];
Trong Node.js, bạn có thể sử dụng mô-đun phân tích của Path ...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
basenamechức năng:path.basename(file)
Con đường đến từ nền tảng nào? Đường dẫn Windows khác với đường dẫn POSIX khác với đường dẫn Mac OS 9 khác với đường dẫn RISC OS khác ...
Nếu đó là một ứng dụng web nơi tên tệp có thể đến từ các nền tảng khác nhau thì không có một giải pháp nào. Tuy nhiên, một cú đâm hợp lý là sử dụng cả '\' (Windows) và '/' (Linux / Unix / Mac và cũng là một thay thế trên Windows) làm dấu tách đường dẫn. Đây là phiên bản không phải RegExp để thêm phần thú vị:
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, giải pháp của bạn không bảo vệ chống lại một chuỗi trống làm đầu vào. Trong trường hợp đó, nó thất bại với TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.
bobince, đây là phiên bản của nickf xử lý các dấu phân cách đường dẫn DOS, POSIX và HFS (và chuỗi rỗng):
return fullPath.replace(/^.*(\\|\/|\:)/, '');
Không ngắn gọn hơn câu trả lời của nickf , nhưng câu trả lời này trực tiếp "trích xuất" câu trả lời thay vì thay thế các phần không mong muốn bằng một chuỗi trống:
var filename = /([^\\]+)$/.exec(fullPath)[1];
Một câu hỏi yêu cầu "lấy tên tệp mà không cần gia hạn" tham khảo tại đây nhưng không có giải pháp nào cho việc đó. Đây là giải pháp được sửa đổi từ giải pháp của Bobbie.
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
Một số khác
var filename = fullPath.split(/[\\\/]/).pop();
Ở đây, phần tách có biểu thức chính quy với một lớp
ký tự Hai ký tự phải được thoát bằng '\'
Hoặc sử dụng mảng để phân chia
var filename = fullPath.split(['/','\\']).pop();
Nó sẽ là cách để tự động đẩy nhiều dải phân cách vào một mảng, nếu cần.
Nếu fullPathđược đặt rõ ràng bởi một chuỗi trong mã của bạn, nó cần phải thoát khỏi dấu gạch chéo ngược !
Giống"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>
Câu trả lời đầy đủ là:
<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>
Ít chức năng bao gồm trong dự án của bạn để xác định tên tệp từ một đường dẫn đầy đủ cho Windows cũng như các đường dẫn tuyệt đối GNU / Linux & 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 thành công cho câu hỏi của bạn, Kiểm tra đầy đủ
<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)
}
Giải pháp này đơn giản và chung chung hơn nhiều, cho cả 'tên tệp' và 'đường dẫn'.
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(".") );
}