我有两个变量:

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

我怎么做呢?


当前回答

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

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

其他回答

function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}

试试这个:

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

以下片段更为准确:

str.replace(/^(.+?)\/*?$/, "$1");

它不是条带/字符串,因为它是一个有效的url。 它去掉带有多个尾随斜杠的字符串。

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

单尾斜杠:

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

单个或连续的尾随斜杠:

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

单前导斜杠:

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

单线或连续的前导斜线:

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

单行斜杠和尾斜杠:

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

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

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

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

我知道这个问题是关于尾随斜杠,但我在搜索修剪斜杠(在字符串字面量的尾部和头部)时发现了这篇文章,因为人们需要这个解决方案,我在这里发布了一个:

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

更新:

正如@Stephen R在评论中提到的,如果你想在字符串字面量的尾部和头部同时删除斜杠和反斜杠,你可以这样写:

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