In: , ,
On: 2008 / 04 / 27
Shorter URL for this post: http://ozh.in/i0

For my next stuff I needed the Javascript equivalents of PHP functions basename() and dirname(). Nothing genius:

javascript

  1. function basename(path) {
  2.     return path.replace(/\\/g,'/').replace( /.*\//, '' );
  3. }
  4.  
  5. function dirname(path) {
  6.     return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');;
  7. }

It obviously supports paths like /home/ozh/stuff.php, http://site.com/file.ext or double backslashed Win32 paths such as C:\\dir\\document.txt.

Edit: Mister Ze in comments points out to PHP.JS, an ongoing project aiming to port PHP to Javascript. Some really neat stuff there.

Shorter URL

Want to share or tweet this post? Please use this short URL: http://ozh.in/i0

Metastuff

This entry "Javascript basename() and dirname()" was posted on 27/04/2008 at 10:09 pm and is tagged with , ,
Watch this discussion : Comments RSS 2.0.

3 Blablas

  1. Ze says:

    You can find many implementation of php functions in javascript here:

    http://kevin.vanzonneveld.net/techblog/article/phpjs_licensing/

    basename() is implemented in php.JS project but no dirname(), propose your code :)

  2. Ozh says:

    Ze ยป cool ! :)

  3. Tarun Nagpal says:

    Thanks. This help

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?