Shortening File Path With Javascript

I ran across this question on Stack Overflow, and I decided to address it: http://stackoverflow.com/questions/14308792/how-to-truncate-a-string-containg-a-path-without-touching-the-filename The problem is basically trying to shorten a file path to a specified length using, while maintaining the filename and the originating drive (clearly meant for Windows application). Here is what I came up with: http://jsfiddle.net/AlienHoboken/y7SgA/ What it does is pretty simple. First, it splits the string on slashes, so we can get the drive letter and file name as the first and last elements.

1
2
3
var tokens = str.split("\\");
var drive = tokens[0];
var fileName = tokens[tokens.length - 1];

Then it takes these items and calculates the length they take up, and finds our remaining length from max length.

1
2
3
var len = drive.length + fileName.length;
//remove the current lenth and also space for 3 dots and 2 slashes
var remLen = maxLength - len - 5;

If we have any length left, ie. we can use some of the intermediary path, it tries to do so. Else it just gives back a path with the drive letter and filename only. The first step of shortening the the intermediary path is to remove the first and last elements, as we are already using them, then join the tokens back together into a string.

1
2
3
4
5
//remove first and last elements from the array
tokens.splice(0, 1);
tokens.splice(tokens.length - 1, 1);
//recreate our path
var path = tokens.join("\\");

Then we need to get the lengths of the first and second sections for the shortened path, the text around our eventual ellipses. In the event the remaining length is an odd number, ceiling one value and floor the other.

1
2
3
//handle the case of an odd length
var lenA = Math.ceil(remLen / 2);
var lenB = Math.floor(remLen / 2);

Finally we rebuild our now shortened path. Taking lenA characters from the front and lenB characters from the end. Then use these parts and put them together with our ellipses and drive / filename to form our new shortened path!

1
2
3
4
//rebuild the path from beginning and end
var pathA = path.substring(0, lenA);
var pathB = path.substring(path.length - lenB);
path = drive + "\\" + pathA + "..." + pathB + "\\" + fileName;

Not too hard of a task, but an interesting one that gives a good example of string manipulation.

Comments