Christian Heilmann

trimMiddle() – the missing String trim method

Friday, January 3rd, 2025 at 4:21 pm

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>

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.

Share on Mastodon (needs instance)

Share on Twitter

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

Dev Digest 146: 🥱 React fatigue 📊 Query anything with SQL 🧠 AI News

Why it may not be needed to learn React, why Deepfake masks will be a big problem and your spirit animal in body fat! 

Dev Digest 147: Free Copilot! Panel: AI and devs! RTO is bad! Pi plays!

Free Copilot! Experts discuss what AI means for devs. Don't trust containers. Mandated RTO means brain drain. And Pi plays Pokemon!

Dev Digest 148: Behind the scenes of Dev Digest & end of the year reports.

In 50 editions of Dev Digest we gave you 2081 resources. Join us in looking back and learn about all the trends this year.

Dev Digest 149: Wordpress break, VW tracking leak, ChatGPT vs Google.

Slowly starting 2025 we look at ChatGPT vs Google, Copilot vs. Cursor and the state of AI crawlers to replace web search…

Dev Digest 150: Shifting manually to AI.

Manual coding is becoming less of a skill. How can we ensure the quality of generated code? Also, unpacking an APK can get you an AI model.

My other work: