DEV Community

Thomas Rigby
Thomas Rigby

Posted on • Originally published at thomasrigby.com on

Trim trailing slash

silver scissors on pink surface

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);

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

.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.

Top comments (0)