DEV Community

Cover image for trimMiddle() - the missing String trim method
Christian Heilmann
Christian Heilmann

Posted on • Originally published at christianheilmann.com

trimMiddle() - the missing String trim method

One of the cool features of MacOS' Finder app is that it does not trim file names that don't fit the space at the end, but in the middle of the file name. This does make a lot more sense, as it also shows what format the file is.

MacOS finder showing long filenames with an ellipsis in the middle of them.

Neither JavaScript nor CSS have a method for that kind of functionality at the moment (although there is a CSS discussion on the matter), so I thought I write one. I give you trimMiddle() as an addition to trimStart and trimEnd.

You can find it:

On NPM: https://www.npmjs.com/package/trimmiddle
On GitHub: https://github.com/codepo8/trimMiddle

and you can play with the demo page to see it in action:

The test page showing the method in action

To use it in your own products, either use npm -​i trimmiddle or use the client-side version via unpkg.

<script src="https://unpkg.com/trimmiddle@0.1.0/clientside.js"></script>
Enter fullscreen mode Exit fullscreen mode

The method allows you to define the amount of letters you want to show and what the character in between the parts should be. Default is 16 characters and the ellipsis character. The script uses the Intl.Segmenter API when the string is longer than the character limit, which means that it also works with strings containing compound Emoji. The normal split or substring methods fail in this case.

Top comments (1)

Collapse
 
grahamthedev profile image
GrahamTheDev

I actually love this so much! Also thanks for introducing me to Intl.Segmenter, that is a really useful one to know!