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
Then it takes these items and calculates the length they take up, and finds our remaining length from max length.
1 2 3
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
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
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
Not too hard of a task, but an interesting one that gives a good example of string manipulation.