parsing filename from a full path+filename

hibbidiji
hibbidiji used Ask the Experts™
on
I am grabbing full paths to files from file input boxes on my web page.   I, therefore have path strings like this:

c:\files\music\myfile.mp3

I might also get it in unix like this:

/usr/home/me/music/myfile.mp3

I would like to get a js function that I can pass strings like these and it will determine if it is windows or *nix and will return just the filename itself: 'myfile.mp3'

help!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2006
Commented:
Is this what you are looking for?  Something that just returns the file name, without the path:

function getNameNoPath(filename) {
  var re = new RegExp(/([^\/\\]+)$/);
  var m = re.exec(filename);
  if (m == null) {
    return null;
  } else {
   return m[0];
  }
}
Top Expert 2005
Commented:

This is a working program,
modify the code as per your need.

to run this, copy the below code, save as html file and open in browser.

code  starts
------------------------------------------
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function mysplit()
{
 temp1 = document.myform.filename.value;
 var temp2 = null;// new Array();

  if (temp1.indexOf(':') !=-1)
  {
      alert("Client OS is Windows");
       temp1 = temp1.substring(2);
       temp2 = temp1.split("\\");
  }else {
          alert("Client OS is Unix");
            temp2 = temp1.split("/");
  }       
 fileName="";

 for(i=0; i<temp2.length; i++) {
      fileName = temp2[i];
 }
 
 alert("File Name :" +fileName);
}
//-->
</SCRIPT>

<BODY>
 <FORM METHOD=POST ACTION="" name="myform">
      <INPUT TYPE="text" NAME="filename" value="c:\files\music\myfile.mp3">
      <input type="button" onClick='mysplit();' />  
 </FORM>
</BODY>
</HTML>

------------------------------------------
code  ends

regards,
AKS

Author

Commented:
Great answers - I just wish the delphi area was as active nowadays

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial