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

Why You Should Blog More (Data)

When you stop blogging, people stop coming. Simple enough. Here's the proof.

Using a Linter Will Make You a Better Dev

Using a linter while you write code won't only make your code better formatted, it'll make you a better programmer.

Everyone Is Self Employed

The idea that you're not self-employed if you work fulltime somewhere is wrong. EVERYONE is self-employed.

The Real Reason to Learn to Code

Not everyone needs to be a programmer, but learning a little bit of coding can help in a lot of different areas.

Review: Keto Diet

I recently gave the Keto (Ketogenic) Diet a try. Suffice to say...it works.

You Don't Need to Get it All Correct Immediately

Too many people wait on shit to be perfect. Get it close, leave out some stuff, and set yourself up to quickly iterate.

Using Foundation 6 in Angular 4 (or 2)

How to use Foundation for Sites 6 in Angular 4 (or any version 2+)

Great Products Need Great DevOps

In the quest for shipping great products, DevOps is often overlooked, and that's a mistake

How I Increased my Water Intake by 500%

We all need to drink more water, but it's hard to get in the habit. Here's a simple trick I used to get a 5x improvement on my intake.

Three Secrets That Made Cutting The Cord Easy

After decades of being attached at the hip to cable, I finally cut the cord, and it's been amazing. Here are three secrets that helped me get the most of it.