Skip to content

Apologies for the appearance of the site. I'm designing in public!

silver scissors on pink surface

Trim trailing slash

Published on Thursday, 1 September 2022.
At 354 words, this article should take about 2 minutes to read.

Sometimes a URL has a trailing slash, sometimes it doesn't. If we can't be certain, we need to handle either eventuality.

Shut up and give me the code!

const trimTrailingSlash = (x) => x.split('').reverse()[0] !== '/' ? x : x.substring(0,x.split('').length -1);

Let's break that down

First off we're creating an arrow function that will accept an input that we're calling x.

Inside the function, x is split into individual characters creating an array. The array is reversed using, well, reverse(). This means we can check the first character ([0]) instead of having to work out what the last character is - smart!

If that character does not equal (!==) a slash simply return the given string. Bouncing out of a function as soon as possible keeps our code quick!

If the character is a trailing slash, we want to get rid of it; to return part of a string, we can use substring.

Substring takes two parameters: the starting index and the finishing index. We will start at 0 which is the very first character and finish with the second to last character (the one before the /).

To figure what that number is we, again, split the string into an array and use the total number of items (.length) minus 1.

Alternative solution!

Using String.prototype.endsWith() and String.prototype.slice(), we can shorten this function - and make it a little more readable! 🎉

  const trimTrailingSlash = (x) => x.endsWith('/') ? x.slice(0,-1) : x;

.endsWith() works exactly how you would imagine: if the string ends with the given character, the method returns true, otherwise it returns false.


To trim a trailing slash from a URL requires two operations;

  1. We must determine if the last character is a slash
  2. If it is, we must remove the slash

Each of these steps can be performed in several ways, you can mix-and-match them how you want.

I've not done any performance testing on these so I couldn't tell you which is fastest when trimming the trailing slash from 40,000 URLs but, unless you are working with 40,000 URLs, just pick the one you feel is the most readable.


Cover image courtesy of Bere del Valle.


In almost all cases, the comments section is a vile cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on Mastodon (which is not a vile cesspool of Reply Guys, racists, and bots).

onward-journeys module