Skip to content
silver scissors on pink surface

Trim trailing slash

Thursday, 1 September 2022

At 456 words, this article should take about 2 minutes to read.

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.

Conclusion

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.


Fin

Comments

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 Twitter (which is, in its own way, a vile cesspool of Reply Guys, racists, and bots).

Thomas Rigby

Thomas Rigby

When I'm not building things for the internet, I take photos of stuff.
Loading Invisible Visible Navigation Close Arrow Info Online Online