views:

69

answers:

2

I recently created a function in javascript that takes in a file name and a max character limit where the result needs to follow these rules:

  • Always include file extension
  • If shrinking occurs, leave the first part and last part of the file name intact.
  • Always replace the removed characters with '...'
  • If file length is under the max then do nothing
  • You can assume the max is a least 5 chars long

Now I've already solved this, but it got me thinking if there is a more elegant or simple way to do this in javascript using regular expressions or some other technique. It also gave me an opportunity to try out jsFiddle. So with that in mind here is my function:

function ReduceFileName(name, max){        
if(name.length > max){        
    var end = name.substring(name.lastIndexOf('.'));
    var begin = name.substring(0, name.lastIndexOf('.'));
    max = max - end.length - 3;
    begin = begin.substr(0,max/2) + '...' + begin.substr(begin.length-(max/2) , max/2 + 1);
    return begin + end;        
}    
return name;
}

And here it is on js Fiddle with tests

A: 

I'm not sure that regular expressions will be necessarily more elegant, but so far I came up with the following which passes your tests:

function ReduceFileName(name, max){        
    if(name.length > max) {
        var ell ="\u2026"; // defines replacement characters
        var ext = (/\.[^\.]*$/.exec(name) || [""])[0]; // gets extension (with dot) or "" if no dot
        var m = (max-ell.length-ext.length)/2; // splits the remaining # of characters
        var a = Math.ceil(m);
        var z = Math.floor(m);
        var regex = new RegExp("^(.{"+a+"}).*(.{"+z+"})"+ext, "");
        var ret = regex.exec(name);
        return ret[1]+ell+ret[2]+ext;
    }
    return name;
}
Timothée Boucher
I realized that there's a problem if the extension is longer or equal to the max number of characters. But your assumptions seem to say that's ok ;-)
Timothée Boucher
Definitely interesting but I agree that it's not really more elegant or simpler. Thanks for the answer though.
Greg Roberts
A: 

Since I didn't get much activity on this, I'm assuming there isn't a much better way to do this, so I'll consider my method as the answer until someone else comes up with something else.

function ReduceFileName(name, max){        
if(name.length > max){        
    var end = name.substring(name.lastIndexOf('.'));
    var begin = name.substring(0, name.lastIndexOf('.'));
    max = max - end.length - 3;
    begin = begin.substr(0,max/2) + '...' + begin.substr(begin.length-(max/2) , max/2 + 1);
    return begin + end;        
}    
return name;
}
Greg Roberts