280

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?

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Ryan
  • 9,821
  • 22
  • 66
  • 101
  • 1
    possible duplicate of [JQuery check and remove slash from the end of URL read](http://stackoverflow.com/questions/4740364/jquery-check-and-remove-slash-from-the-end-of-url-read) – Hugo Jan 29 '14 at 08:17

12 Answers12

622

Try this:

function someFunction(site)     
{     
    return site.replace(/\/$/, "");
} 
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • 166
    To handle cases with multiple trailing slashes, you can use: `return site.replace(/\/+$/, "");` – mikermcneil Feb 21 '12 at 18:48
  • 19
    "/".replace(/\/$/, "") will be "". "/" is a valid path and it shouldn't be stripped. – puchu Jul 19 '16 at 16:15
  • 4
    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 Dec 12 '21 at 02:07
  • 1
    @Trott can you suggest some answer which isn't susceptible to that attack? – Gourav Dec 14 '21 at 06:59
  • 2
    @Gourav `function removeAllTrailingSlashes(str) {let i = str.length; while (str[--i] === '/'); return str.slice(0, i+1);}` – Trott Dec 14 '21 at 12:09
  • @Trott ah thanks! I've been looking through lots of regex lately, seems like I started forgetting this basic stuff xD – Gourav Dec 17 '21 at 07:08
  • This one will not work for `document.referrer` where you could have the protocol `https://stackoverflow.com/` – Искрен Станиславов Apr 05 '23 at 12:03
  • To ensure you're only removing a trailing slash prefixed with a word, you can use `site.replace(/(?<=\w)\/+/, '')`. This uses the positive lookbehind pattern `(?<=)` to ensure that the match is prefixed by a word `\w`. See this [RegEx](https://regexr.com/7e056). – Jaime Still May 17 '23 at 18:57
95

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;
};
Seth Holladay
  • 8,951
  • 3
  • 34
  • 43
88
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.

Lane
  • 6,532
  • 5
  • 28
  • 27
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
ChronosLLC
  • 593
  • 3
  • 8
28

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 [\\/]

Stephen R
  • 3,512
  • 1
  • 28
  • 45
  • 2
    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. – Trott Dec 12 '21 at 02:11
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'
vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • This is the real answer! – Can PERK Aug 15 '18 at 13:43
  • 2
    If you want to trim both slashes and backslashes: `.replace(/^[\\/]+|[\\/]+$/g, '')` – Stephen R Sep 19 '19 at 22:25
  • 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. – Trott Dec 12 '21 at 02:10
12

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.
1ven
  • 6,776
  • 1
  • 25
  • 39
  • While this may be a valid approach to removing multiple slashes, that's not the request of the OP. – Jon L. Apr 18 '19 at 15:30
  • @JonL. Many people browse stack overflow to find answer. I find this answer helpful than the accepted answer. – Ronnel Martinez Mar 03 '20 at 21:09
  • 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. – doctorgu Oct 21 '20 at 05:52
  • 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. – Trott Dec 12 '21 at 02:13
4
function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

another solution.

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);
DevJ3rry
  • 666
  • 6
  • 22
2

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.

Barkermn01
  • 6,781
  • 33
  • 83
-4

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
Massimo
  • 183
  • 1
  • 4
-13
function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}
josh.trow
  • 4,861
  • 20
  • 31
  • 2
    `subtring`? Besides that, it removes the first slash and everything after it. – ThiefMaster Jul 13 '11 at 14:54
  • @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. – josh.trow Jul 13 '11 at 14:56
  • Well his comment says he wants to remove the trailing slash – ThiefMaster Jul 13 '11 at 14:58
  • @ThiefMaster: Which, according to his examples, my code does. – josh.trow Jul 13 '11 at 15:03
  • 1
    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* – Barkermn01 Jun 07 '12 at 23:32