Help us understand the problem. What is going on with this article?

Coffee ScriptでRubyの`basename`や`dirname`みたいな関数を使う

More than 5 years have passed since last update.

ありそうだと思ったのに、意外となかったので半分ぐらいコピペで作りました。

basename = (path,ext="") ->
  base = new String(path).substring(path.lastIndexOf('/') + 1)
  base.replace(new RegExp(ext+'$','g'),"")

dirname = (path) -> path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '')

basename("foo/bar.txt",".txt")みたいに使います。ただbasename("foo/bar.txt","xt") #-> bar.t のように第二引数が拡張子でなくても反応するのでちょっと注意。

一応Javascriptも

やっぱりCoffee使ってる人よりもJSで書いてる人の方が多いのでJavascriptのコードも載せておきます。
自動生成されたコードだけどまあやってることは同じです。こうしてみると無駄に長いですね。

  var basename, dirname;

  basename = function(path, ext) {
    var base;
    if (ext == null) {
      ext = "";
    }
    base = new String(path).substring(path.lastIndexOf('/') + 1);
    return base.replace(new RegExp(ext + '$', 'g'), "");
  };

  dirname = function(path) {
    return path.replace(/\\/g, '/').replace(/\/[^\/]*$/, '');
  };

参考

string - Need a basename function in Javascript - Stack Overflow
http://stackoverflow.com/questions/3820381/need-a-basename-function-in-javascript

Javascript basename() and dirname() « planetOzh
http://planetozh.com/blog/2008/04/javascript-basename-and-dirname/

coffeescript - How to rewrite a javascript replace code to coffee script - Stack Overflow
http://stackoverflow.com/questions/19417726/how-to-rewrite-a-javascript-replace-code-to-coffee-script/19417765?noredirect=1#19417765

ironsand
思いついたアイデアをすぐに形にできる能力を身につけたいのでRailsを頑張って習得中。仕事ください。
http://programming.ironsand.net/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away