In: , ,
On: 2008 / 04 / 27 Viewed: 12237 times

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.

Related posts

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. You can trackback this post from your own site

2 Blablas

  1. 1
    Ze France »
    commented, on 28/Apr/08 at 12:07 am # :

    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. 2
    Ozh France »
    said, on 28/Apr/08 at 12:40 am # :

    Ze » cool ! :)

Leave a Reply

Comment Guidelines or Die

  • HTML: You can use these tags: <a href=""> <em> <i> <b> <strong> <blockquote>
  • Posting code: Post raw code (no <> &lt; etc) within appropriate tags : [php][/php], [css][/css], [html][/html], [js][/js], [sql][/sql], [xml][/xml], or generic [code][code]
  • Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar.
  • Spam: Various spam plugins on patrol. I'll put pins in a Voodoo doll if you spam me.
  • I will mark as Spam test comments, all comments with SEO names (ie "My Cool Online Shop" instead of "Joe") or containing forum-like signatures.

Read more ?

Close
E-mail It