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 のように第二引数が拡張子でなくても反応するのでちょっと注意。



  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

Javascript basename() and dirname() « planetOzh

coffeescript - How to rewrite a javascript replace code to coffee script - Stack Overflow

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