Trim trailing slash
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.
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
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.
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).