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

Required Reading for All Couples

If you're married, about to get married, or just committed to someone for a long period of time, these three books are absolutely required reading.

I Launched a New Podcast, and I Want You to Call In

I just launched a new podcast called Design By Committee, dedicated to answering your questions about UX, product design, content, strategy and anything else tech.

Shitty Sales Have Made Product Development Harder

Shitty, one-sided sales processes have made product development much more difficult for early stage startups.

Why I'm Cold Emailing You

You might have gotten a cold email from me. Tasteless? Some people think so. Here's why I'm doing it.

How I Found Your Email

I've been cold emailing a lot of people, and many folks are surprised that I found their email. Here's where I dug it up.

Sales is User Research, Undercover

Announcement: The Most Exciting Thing I've Done

Today, I'm announcing the most exciting project I've been involved with. It's called CrowdSync, and it helps to automate paperwork, communication and logistics when dealing with groups of people. Read on for why this is so big.

Three Ways to Start Talking to Users

How to Post to Private Slack Channels from Zapier

If you automate posting to Slack via Zapier, you might need to post to a private channel. It's not entirely obvious how to do it, but actually pretty damn easy.

A Peek Inside our UX Process