299

I have two variables:

site1 = "www.somesite.com";  
site2 = "www.somesite.com/";  

I want to do something like this

function someFunction(site)
{
    // If the var has a trailing slash (like site2), 
    // remove it and return the site without the trailing slash
    return no_trailing_slash_url;
}

How do I do this?

1

13 Answers 13

642

Try this:

function someFunction(site)     
{     
    return site.replace(/\/$/, "");
} 
Sign up to request clarification or add additional context in comments.

9 Comments

To handle cases with multiple trailing slashes, you can use: return site.replace(/\/+$/, "");
"/".replace(/\/$/, "") will be "". "/" is a valid path and it shouldn't be stripped.
Be careful with /\/+$/, which is in a comment here that is upvoted 150 times at the time of this writing. It is subject to ReDoS. That doesn't matter in a lot of cases, but could be a big problem if you are using this (for example) in server-side Node.js code.
@Trott can you suggest some answer which isn't susceptible to that attack?
@Gourav function removeAllTrailingSlashes(str) {let i = str.length; while (str[--i] === '/'); return str.slice(0, i+1);}
|
111

ES6 / ES2015 provides an API for asking whether a string ends with something, which enables writing a cleaner and more readable function.

const stripTrailingSlash = (str) => {
    return str.endsWith('/') ?
        str.slice(0, -1) :
        str;
};

3 Comments

best solution in 2019 🤙
@PaulRad While using this soln, getting issue of str.slice(0, -1) branch not covered for this line on unit test. How to fix that?
@BijayRai that means your tests are missing a case where str ends with a / slash. You should have two assertions (or two tests), one with a slash and one without.
89
function stripTrailingSlash(str) {
    if(str.substr(-1) === '/') {
        return str.substr(0, str.length - 1);
    }
    return str;
}

Note: IE8 and older do not support negative substr offsets. Use str.length - 1 instead if you need to support those ancient browsers.

2 Comments

Really like the use of term 'ancient' here.
function stripTrailingSlash(str) { if(str.startsWith("/")) { return str.substr(1, str.length - 1); } return str; } NOT FOR IE8... who uses IE8 anyway ?
34

I'd use a regular expression:

function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}

You'll want to make sure that the variable site is a string, though.

1 Comment

I totally agree, anytime you write regex, it should be wrapped in a function with a descriptive name or with comments.
34

Based on @vdegenne 's answer... how to strip:

Single trailing slash:

theString.replace(/\/$/, '');

Single or consecutive trailing slashes:

theString.replace(/\/+$/g, '');

Single leading slash:

theString.replace(/^\//, '');

Single or consecutive leading slashes:

theString.replace(/^\/+/g, '');

Single leading and trailing slashes:

theString.replace(/^\/|\/$/g, '')

Single or consecutive leading and trailing slashes:

theString.replace(/^\/+|\/+$/g, '')

To handle both slashes and backslashes, replace instances of \/ with [\\/]

1 Comment

Some of the solutions here, such as /\/+$/g are susceptible to ReDoS so care must be taken if using on server-side code, for example.
21

I know the question is about trailing slashes but I found this post during my search for trimming slashes (both at the tail and head of a string literal), as people would need this solution I am posting one here :

'///I am free///'.replace(/^\/+|\/+$/g, ''); // returns 'I am free'

UPDATE:

as @Stephen R mentioned in the comments, if you want to remove both slashes and backslashes both at the tail and the head of a string literal, you would write :

'\/\\/\/I am free\\///\\\\'.replace(/^[\\/]+|[\\/]+$/g, '') // returns 'I am free'

3 Comments

This is the real answer!
If you want to trim both slashes and backslashes: .replace(/^[\\/]+|[\\/]+$/g, '')
The solutions in this answer are subject to ReDoS attacks, so you may wish to avoid them if they are being used in server-side code (using Node.js or deno, for example). Depending on where the path is coming from, you may want to use caution with browser code too.
13

This snippet is more accurate:

str.replace(/^(.+?)\/*?$/, "$1");
  1. It not strips / strings, as it's a valid url.
  2. It strips strings with multiple trailing slashes.

4 Comments

While this may be a valid approach to removing multiple slashes, that's not the request of the OP.
@JonL. Many people browse stack overflow to find answer. I find this answer helpful than the accepted answer.
I think this is more simpler -> (.+?)\/+$. No need to use ^ at first because . will search from the start anyway, No need to use *? at before $ because it will be return original string when regex pattern not matched.
This answer is highly susceptible to ReDos and should probably be avoided in server-side code and other contexts where ReDoS attacks are a concern.
4
function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

another solution.

2 Comments

this won't work if you have string = "/"
This wont work for URLs - you will have http:// changed to http:/
3

The easiest way I know of is this:

function stripTrailingSlash(str){
   if(str.charAt(str.length-1) == "/"){ str = str.substr(0, str.length - 1);}
   return str
}

Updates ES2015 version.

const stripTrailingSlash = str=>str.charAt(str.length-1)=="/"?str.substr(0,str.length-1):str;

This will then check for a / on the end and if it's there, remove it. If it's not, it will return your string as it was.

Fixed the calculation for zero-based index on the string.

EDIT: As there was a comment to one response there are now more doing the same thing do not use sub string for a comparison, you're creating a whole new string in memory (at the low level) when you can use charAt to get a single char a lot less memory to do your comparison, Javascript is still JIT and can't do the optimisations to the level any lang going though a compiler can, it won't fix this for you.

Comments

3
const url = new URL("https://some.site/some/path/?somekey=somevalue");
url.pathname.endsWith('/') && (url.pathname = url.pathname.slice(0, -1));
url.toString() // 'https://some.site/some/path?qk=213&hded=444';

Comments

2

Here a small url example.

var currentUrl = location.href;

if(currentUrl.substr(-1) == '/') {
    currentUrl = currentUrl.substr(0, currentUrl.length - 1);
}

log the new url

console.log(currentUrl);

Comments

-6

In case you are working with URLs then you can use the built-in URL class

const url = new URL('https://foo.bar/');
console.log(url.toString()); // https://foo.bar

2 Comments

url.toString will not remove the slash
You should test your code before answering. It results in https://foo.bar/.
-13
function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}

5 Comments

subtring? Besides that, it removes the first slash and everything after it.
@ThiefMaster: Really? You can't tell that I meant substring? Also yes, I meant to remove the first slash and everything after it since it does fill the bill for the question and example data posted.
Well his comment says he wants to remove the trailing slash
@ThiefMaster: Which, according to his examples, my code does.
Just a not why not to use this at any point if the urls change to be "fully-qualified" have http:// this wont work and any links with / in the middle wont work for googlers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.