我有两个变量:

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

我怎么做呢?


当前回答

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

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

更新:

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

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

其他回答

如果你正在使用URL,那么你可以使用内置的URL类

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

这里有一个小的url示例。

var currentUrl = location.href;

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

记录新的url

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

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

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

我会使用正则表达式:

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 ($)
}

但是,您需要确保变量site是一个字符串。