Trim trailing slash
At 366 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() !== '/' ? 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
Inside the function,
split into individual characters creating an array. The array is reversed using, well,
reverse(). This means we can check the first character (
) 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 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.
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
To trim a trailing slash from a URL requires two operations;
- We must determine if the last character is a slash
- 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.
Real. Simple. Syndication.
Get my latest content in your favorite RSS reader. I use InoReader but you don't have to.
What even is an RSS feed?!Subscribe