Borislav Hadzhiev
Tue Oct 26 2021·3 min read
Photo by Artem Beliaikin
To remove a trailing slash from a string, call the replace
method with the
following regular expression /\/+$/
as the first parameter and an empty string
as the second. The replace
method will strip the trailing slash and return a
copy of the string.
function removeTrailingSlash(str) { return str.replace(/\/+$/, ''); } // 👇️ "example.com" console.log(removeTrailingSlash('example.com/')); // 👇️ "example.com" console.log(removeTrailingSlash('example.com///')); // 👇️ "example.com" console.log(removeTrailingSlash('example.com'));
We used the String.replace method to get a new string that doesn't contain any trailing slashes.
We passed the following 2 parameters to the replace
method:
The forward slashes / /
mark the beginning and end of the regular expression.
The plus +
matches the preceding item (the forward slash) 1 or more times.
And the dollar $
sign matches the end of the input.
In its entirety the regular expression matches one or more trailing slashes at the end of the string.
If you ever need help reading a regular expression, check out this regex cheatsheet from MDN. It's by far the best one out there.
replace
method does not change the original string, it returns a new string with one or more matches replaced. Strings are immutable in JavaScript.An alternative approach is to use the String.endsWith method.
To remove a trailing slash from a string:
endsWith()
method on the string and check if it ends with a slash.slice
method to remove the last character
from the string.function removeTrailingSlash(str) { return str.endsWith('/') ? str.slice(0, -1) : str; } // 👇️ "example.com" console.log(removeTrailingSlash('example.com/')); // 👇️ "example.com" console.log(removeTrailingSlash('example.com'));
We used the String.endsWith method to check if the string ends with a slash character.
The method returns true
if the string ends with the supplied character and
false
otherwise.
We used a ternary operator, which is very similar to an if / else statement.
If the string ends with a slash, we call the String.slice method and return the entire string up to the last character.
We passed the following parameters to the slice
method:
-1
means go up to, but not including the last character
of the string0
and the last - string.length - 1
.-1
and str.length - 1
is the same. We instruct the slice
method to go up to, but not including the last character in the string.If the string doesn't end with a slash, we simply return the string.
Note that this approach doesn't handle the scenario where the string ends with
multiple slashes. We only remove the last character using the slice
method.