Friday, January 23, 2009

Get a Filename from a Path in Javascript

Here's a quick Javascript function that will parse the filename from a path using regex.  It looks for any letter or digit, hyphen, or underscore followed by a dot (.) followed by a letters or numbers for the extension.

function getFileName(path) {
    return path.match(/[-_\w]+[.][\w]+$/i)[0];
}

8 comments:

  1. Hi, what i don't want the extension, how should i return the path. Thanks.

    ReplyDelete
  2. not working for filenames having empty spaces.

    ReplyDelete
  3. Just tweak the regex a bit. This will look for any character that isn't a forward slash or dot so you can have special chars in the filename as well:

    [^/]+[.][\w]+$

    ReplyDelete
  4. i want to get file name from directory and then display on web page using javascript

    ReplyDelete
  5. Thanks man! You save my time!!! Thank you!!!

    ReplyDelete
  6. The regex you are using is not Accurate , dosn't get all kind of names

    ReplyDelete
  7. Thanks your function helped alot....

    ReplyDelete
  8. This won't match if you have other characters that arent hyphens or underscores (like percent signs for url encoded characters). What i ended up doing was just slicing at / and popping the last one off the end.

    function getFileName(path) {
    return path.split('/').pop();
    }

    ReplyDelete