How to Trim the End of a Path in Javascript


I came across a situation recently where I needed to trim the end of a path in Javascript, and figured I’d share the quick, one-line solution, in case you need to do the same sometime.

Here’s the deal: I had a filepath that I needed to trim the filename off of, leaving just the path. So, I had this: /path/to/filename.jpg, and needed to trim that to /path/to.

The easiest way to do it? Use the lastIndexOf() method to find the last occurance of the slash, and trim from there, like this:


var string = '/path/to/filename.jpg'
var trimmedString = string.substr(0, string.lastIndexOf('/'));

console.log(trimmedString); // '/path/to'

Super easy. I’d considered using some variation of split('/'), but stumbled upon lastIndexOf(), which works much better. lastIndexOf() does just what it sounds like: gives you back the index of the last occurance of that character in the string. Using that inside of substr(), you can have it take the substring from the beginning, up to that indexed character. Piece of cake!

Hope this helps you if you need to trim the end of a path. Great for filepaths, and even for paths that might be in dot notation.

Related Posts

The Art of Finding a Way

Being resourceful and relentless is one of the keys to being successful (and a great shipper). When in doubt, find a way.

Why I Have a Cocktail at 3:30 Every Day

Every day at 3:30, I stop what I'm doing and have a cocktail. It's become an incredibly important part of my daily routine.

Everyone In a Startup Should Have This Skill

You know you need technical skills to build the product, and sales skills to sell it, but does your team have this critical skill?

Doing Things Makes You Feel Better

If you're feeling down, depressed or just in a blah mood, do something. Anything. Make a thing, clean a room. Action makes you feel better.

Review: Auth0

Auth0 is a service that provides identity as a service, so you never have to build authentication again. Here, I lay out the good and the bad.

Why I Unfollowed Everyone on Twitter

I unfollowed everyone (~4,500 people) on Twitter. Here's why I'd do such an insane thing.

How to Turn Off Facebook Live Notifications

Facebook Live is cool, but the constant notifications about new videos aren't. Here's how to turn them off and get some peace.

If You Don't Have a Feedback System, It's Not Agile

Everyone loves to throw around the 'agile' word, when talking about how they approach development. But, who's actually doing it, and who's just pretending?

When Employee Retention is a Bad Thing

Having employees that stay around for awhile is a great thing, right? Maybe not always.

Review: Project 333

In a desparate attempt to declutter our space, we gave this radical program a try. Game changer, for sure.