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

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.

Just Because You Don't Like It, Doesn't Mean It Doesn't Work

Sometimes, things you can't believe work actually do. Just because you hate something doesn't mean it's not effective.

There's no such thing as B2B

B2B doesn't exist. You're always selling B2C.

Review: Figma

A look inside of one of the newest tools out there for user experience and visual designers.

How I'm Planning My Meals This Year

Eating is something we all have to do every day, and with a solid plan, you can keep it efficient and healthy. Here's how I'm planning out my meals, so it doesn't distract me from the important things.

My 2017 Reading Plan (And How to Read 50 Books this Year)

How I'm setting myself up to crush my reading goals, and how you can do it too.

Strength Training with Stronglifts 5x5

Looking for a workout program that gets results and keeps you on an intentional plan? Check out Stronglifts.