回答:
var filename = fullPath.replace(/^.*[\\\/]/, '')
これはパスで\ OR /の両方を処理します
"/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では、Pathの解析モジュールを使用できます ...
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パスとは異なります...
ファイル名が異なるプラットフォームから取得される可能性があるWebアプリの場合、解決策は1つではありません。ただし、妥当なスタブは、パス区切り文字として「\」(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、これはDOS、POSIX、およびHFSパス区切り文字(および空の文字列)を処理するnickfのバージョンです。
return fullPath.replace(/^.*(\\|\/|\:)/, '');
別のもの
var filename = fullPath.split(/[\\\/]/).pop();
ここで分割には、文字クラス
の正規表現があります。2つの文字は「\」でエスケープする必要があります
var filename = fullPath.split(['/','\\']).pop();
必要に応じて、より多くのセパレータを配列に動的にプッシュする方法になります。コード内の文字列によって明示的に設定されている
場合fullPathは、バックスラッシュをエスケープする必要があります。
お気に入り"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>
完全な答えは次のとおりです。
<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(".") );
}