Explain Codes LogoExplain Codes Logo

Return string without trailing slash

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Nov 15, 2024
TLDR

Let's trim it — remove the trailing slash from your URL using .replace() with a regular expression or regex:

let result = str.replace(/\/$/, "");

This regex /\/$/ targets a rear slash (i.e, /) that's at the end of the string (i.e, $). The slash is trimmed off, much like unwanted nose hair👃✂️.

How to deal with different URL formats

URLs, like human moods, can come in various formats, and here's how you deal with them.

ES6 optimized: Using endsWith and slice

Modern browsers, they're fancy🎩. So we'll do this in style using ES6 features:

let cleanUrl = (url) => url.endsWith('/') ? url.slice(0, -1) : url;

Here, we politely ask if the URL endsWith a slash and, if it does, we slice it off. No hard feelings, /.

Antique gold: substr method for older browsers

If you're dealing with an audience straight outta the stone age (aka older browsers), here's the trusted substr way:

function removeTrailingSlash(url) { if (typeof url === 'string') { return url.substr(-1) === '/' ? url.substr(0, url.length - 1) : url; } else { throw new Error('Input expected to be a string, not a dinosaur 🦖'); } }

Our trusty substr is ensuring compatibility with older browsers. Plus, in the unlikely event our URL is not a string, it ensures Jurassic Park stays closed.

For the stubborn ones: Edge cases

What's the procedure to tackle URLs that end with multiple slashes or spaces before the slash? Here:

url = "https://example.com// ".replace(/\s+$/, '').replace(/\/+$/, "");

In just one shot, no chit-chat, we trim any whitespace with \s+$, then remove mountain-like stacks of trailing slashes with \/+$.

Removing both leading and trailing slash

While we're at it, let's talk about leading slashes:

let removeLeadTrainSlash = (url) => url.replace(/^\/+|\/+$/g, '')

This regex is the superstar — it removes both leading and trailing slashes. Double action, one shot.

Building robust solutions

Now, let's look at how you can deal with both forward and backward slashes.

Regex for multiple slash types

If you're dealing with a mix of slashes (because who are we to judge?), here's a regex that can handle those:

url = "https://example.com\\\\".replace(/[\\/]+$/, "");

We show all slashes, forward and backward, the exit door.

Chain string methods for better control

For complete control over slash-removal, you can chain string methods:

url = "https://example.com/".split('/').filter(Boolean).join('/');

This approach splits the URL by slashes, filters out empty strings, and then joins them back together.