tags:

views:

13568

answers:

6

Hello,

Just wondering, is there any way that I can get the last value (based on the '\' symbol) from a full path? Example:

C:\Documents and Settings\img\recycled log.jpg

With this case, I just want to get "recycled log.jpg" from the full path in javascript.

+18  A: 
var filename = fullPath.replace(/^.*\\/, '')
nickf
+5  A: 

What platform does the path come from? Windows paths are different from POSIX paths are different from Mac OS 9 paths are different from RISC OS paths are different...

If it's a web app where the filename can come from different platforms there is no one solution. However a reasonable stab is to use both '\' (Windows) and '/' (Linux/Unix/Mac and also an alternative on Windows) as path separators. Here's a non-RegExp version for extra fun:

var leafname= pathname.split('\\').pop().split('/').pop();
bobince
You may want to add that classic MacOS (<= 9) used colon separators (:), but I'm not aware of any browsers that may still be in use that didn't translate MacOS paths to POSIX paths in the form of file:///path/to/file.ext
eyelidlessness
You can just use pop() instead of reverse()[0]. It modifies the original array too but it's okay in your case.
Chetan Sastry
Yeah, that's a good idea. Edited, ta!
bobince
A: 

Not more concise than nickf's answer, but this one directly "extracts" the answer instead of replacing unwanted parts with an empty string:

var filename = /([^\\]+)$/.exec(fullPath)[1];
Ates Goral
+2  A: 

Ates, your solution doesn't protect against an empty string as input. In that case, it fails with "TypeError: /([^(\|\/|\:)]+)$/.exec(fullPath) has no properties".

bobince, here's a version of nickf's that handles DOS, POSIX, and HFS path delimiters (and empty strings): return fullPath.replace(/^.*(\|\/|\:)/, '');

A: 
<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>
A: 
<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>
Semere Hailu