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:

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: 🕹️ Super Mario AI 🔑 API keys in LLMs 🤙🏾 Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: