How to truncate a string (containing a path) without touching the filename (keep the last folder, the filename and the drive letter)?
Hi,
I’m looking for a way to truncate a path to fit a specified width.
I already search on SO and I found this:
Truncate a string nicely to fit within a given pixel width
But it’s adding … at the end of the string. I would like to have a similar function but it need to keep the begining and the ending..
For exemple, I have this path (string):
H:\Informatique\Personnalisation\Icones\__\Crystal GT PNG Pack\Applications\licq.png
And it need to fit the div’s width like this:
H:\Informatique\...PNG Pack\Applications\licq.png
Another exemple:
D:\A___VERY___________LONG________PATH____________\myfile.png
Will be shorten to:
D:\A___VERY___________LONG________PA...\myfile.png
Last exemple:
D:\A___VERY___________LONG________PATH____________\and-a-sub-solder\myfile.png
Will be shorten to:
D:\A___VERY________...\and-a-sub-solder\myfile.png
Restriction:
- The drive part is required (H:)
- The filename and the extension is required (licq.png)
- If there’s multiple folders, the last folder must not be truncate, exept if everything is already truncated and it is the only way to
make the string shorter. - If the filename is too long, truncate it in the middle.
Long filename exemple:
D:\my____file___________________________name____is___too____________long.png
Will be shorten to:
D:\my____file_________..._is___too____________long.png
I see windows and apple doing it the nice way… but I can’t find any script that is near that.
Any link with similar script so I can try adjust it?
Or anybody who wants to help me with that? 🙂
Thank you very much
That’s an interesting problem, here is my solution: http://jsfiddle.net/AlienHoboken/y7SgA/
It assumes that you have a variable str with the path in it, and maxLength with your max character length.
You will need to change code slightly as str is hard coded, you’ll need to change maxLength, and you’ll need to change where you write the information too (it just writes to body right now).
NB: If your drive name + file name exceed the maxLength variable, it will just print out those two together, even though they are too large.
Code, incase you don’t like jsfiddle: