Last active
January 14, 2023 08:44
-
-
Save jens1101/9f3faa6c2dae23537257f1c3d0afdfdf to your computer and use it in GitHub Desktop.
Regex remove trailing slashes from a URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} url | |
*/ | |
function removeTrailingSlashes(url) { | |
return url.replace(/\/+$/, ''); //Removes one or more trailing slashes from URL | |
} |
Thanks for this! For me this failed when the slash was at the end of a url with a querystring (
example.com/?q=something
). I tried getting fancy and make the regex match all in one pattern, but settled on this after 15 minutes...
url.replace(/(?:\/+(\?))/, '$1').replace(/\/+$/, '')
@unledrob - that's not really an issue as the trailing slash appears to be a problem when the URL doesn't have params. If there are params you're best of actually removing those either before or with the trailing slash.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this! For me this failed when the slash was at the end of a url with a querystring (
example.com/?q=something
). I tried getting fancy and make the regex match all in one pattern, but settled on this after 15 minutes...url.replace(/(?:\/+(\?))/, '$1').replace(/\/+$/, '')