我有两个变量:

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

我想做这样的事情

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

我怎么做呢?


当前回答

function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

另一个解决方案。

其他回答

function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

另一个解决方案。

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

注意:IE8及以上版本不支持负子str偏移量。如果您需要支持那些古老的浏览器,请使用str.length - 1。

根据@vdegenne的回答…如何脱衣:

单尾斜杠:

theString。取代 (/\/$/, '');

单个或连续的尾随斜杠:

theString。回到(\ $ / + / g ');

单前导斜杠:

theString。取代 (/^\//, '');

单线或连续的前导斜线:

theString。回想起(^ \ / + / g ');

单行斜杠和尾斜杠:

theString。取代 (/^\/|\/$/ 克,”)

单个或连续的前导斜杠和尾斜杠:

theString。replace (/^\/+|\/+$/ g,”)

要同时处理斜杠和反斜杠,可以将\/实例替换为[\\/]

试试这个:

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

ES6 / ES2015提供了一个API,用于询问字符串是否以某个内容结尾,这使得编写一个更清晰、更可读的函数成为可能。

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