parsing filename from a full path+filename

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


I might also get it in unix like this:


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'

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2006
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

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
<TITLE> New Document </TITLE>
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("/");

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

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

code  ends



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