มีวิธีที่ฉันสามารถรับค่าสุดท้าย (ตามสัญลักษณ์ '\') จากเส้นทางแบบเต็มหรือไม่
ตัวอย่าง:
C:\Documents and Settings\img\recycled log.jpg
ด้วยกรณีนี้ฉันเพียงต้องการได้รับrecycled log.jpgจากเส้นทางแบบเต็มใน JavaScript
มีวิธีที่ฉันสามารถรับค่าสุดท้าย (ตามสัญลักษณ์ '\') จากเส้นทางแบบเต็มหรือไม่
ตัวอย่าง:
C:\Documents and Settings\img\recycled log.jpg
ด้วยกรณีนี้ฉันเพียงต้องการได้รับrecycled log.jpgจากเส้นทางแบบเต็มใน JavaScript
คำตอบ:
var filename = fullPath.replace(/^.*[\\\/]/, '')
สิ่งนี้จะจัดการทั้ง \ OR / ในเส้นทาง
replaceเป็นมากช้ากว่าsubstrซึ่งสามารถใช้ร่วมกับlastIndexOf('/')+1: jsperf.com/replace-vs-substring
"/var/drop/foo/boo/moo.js".replace(/^.*[\\\/]/, '')ผลตอบแทนmoo.js
เพื่อประสิทธิภาพการทำงานฉันได้ทดสอบคำตอบทั้งหมดที่ให้ไว้ที่นี่:
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
และผู้ชนะคือคำตอบสไตล์Split and PopขอบคุณBobince !
path.split(/.*[\/|\\]/)[1];
ใน Node.js คุณสามารถใช้โมดูลการแยกวิเคราะห์พา ธ ...
var path = require('path');
var file = '/home/user/dir/file.txt';
var filename = path.parse(file).base;
//=> 'file.txt'
basenameฟังก์ชั่น:path.basename(file)
เส้นทางมาจากแพลตฟอร์มอะไร เส้นทาง Windows แตกต่างจากเส้นทาง POSIX แตกต่างจากเส้นทาง Mac OS 9 เส้นทางแตกต่างจากเส้นทาง RISC OS แตกต่างกัน ...
หากเป็นแอปพลิเคชันบนเว็บที่ชื่อไฟล์สามารถมาจากแพลตฟอร์มที่แตกต่างกันก็ไม่มีวิธีแก้ปัญหา อย่างไรก็ตามการแทงที่เหมาะสมคือการใช้ทั้ง '\' (Windows) และ '/' (Linux / Unix / Mac และเป็นทางเลือกบน Windows) เป็นตัวคั่นพา ธ นี่คือรุ่นที่ไม่ใช่ RegExp เพื่อความสนุกสนานเป็นพิเศษ:
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 โซลูชันของคุณไม่ได้ป้องกันสตริงว่างเปล่าเป็นอินพุต TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no propertiesในกรณีที่มันล้มเหลวด้วย
bobince นี่คือเวอร์ชันของ nickf ที่จัดการตัวคั่นเส้นทาง DOS, POSIX และ HFS (และสตริงว่าง):
return fullPath.replace(/^.*(\\|\/|\:)/, '');
บรรทัดโค้ด JavaScript ต่อไปนี้จะให้ชื่อไฟล์แก่คุณ
var z = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
alert(z);
คำถามที่ถามว่า "รับชื่อไฟล์โดยไม่มีนามสกุล" อ้างถึงที่นี่ แต่ไม่มีวิธีแก้ปัญหาสำหรับเรื่องนั้น นี่คือโซลูชันที่แก้ไขจากโซลูชันของ Bobbie
var name_without_ext = (file_name.split('\\').pop().split('/').pop().split('.'))[0];
อีกอันหนึ่ง
var filename = fullPath.split(/[\\\/]/).pop();
ที่นี่แยกมีการแสดงออกปกติกับคลาส
ตัวละครตัวละครทั้งสองจะต้องหลบหนีด้วย '\'
หรือใช้อาร์เรย์เพื่อแยก
var filename = fullPath.split(['/','\\']).pop();
มันจะเป็นวิธีที่จะผลักดันตัวแยกมากขึ้นในอาร์เรย์แบบไดนามิกถ้าจำเป็น
หากfullPathมีการกำหนดอย่างชัดเจนโดยสตริงในรหัสของคุณจะต้องหลบหนีแบ็กสแลช !
ชอบ"C:\\Documents and Settings\\img\\recycled log.jpg"
ฉันใช้:
var lastPart = path.replace(/\\$/,'').split('\\').pop();
มันแทนที่ล่าสุด\ดังนั้นจึงสามารถใช้งานกับโฟลเดอร์ได้
<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>
ฟังก์ชั่นเล็ก ๆ น้อย ๆ ที่จะรวมไว้ในโครงการของคุณเพื่อกำหนดชื่อไฟล์จากเส้นทางแบบเต็มสำหรับ Windows รวมถึงเส้นทางสัมบูรณ์ 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 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('/'));