Skip to content

Instantly share code, notes, and snippets.

@jens1101
Last active January 14, 2023 08:44
Show Gist options
  • Save jens1101/9f3faa6c2dae23537257f1c3d0afdfdf to your computer and use it in GitHub Desktop.
Save jens1101/9f3faa6c2dae23537257f1c3d0afdfdf to your computer and use it in GitHub Desktop.
Regex remove trailing slashes from a URL
/**
* @param {string} url
*/
function removeTrailingSlashes(url) {
return url.replace(/\/+$/, ''); //Removes one or more trailing slashes from URL
}
@unledrob
Copy link

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(/\/+$/, '')

@z5Levi
Copy link

z5Levi commented Feb 18, 2021

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