Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return string without trailing slash

Try this:

function someFunction(site)     
{     
    return site.replace(/\/$/, "");
} 

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.


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;
};

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.


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