返回不带尾部斜杠的字符串。

282

我有两个变量:

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

我该怎么做?


1
可能是JQuery检查并删除URL末尾的斜杠的重复问题。 - Hugo
12个回答

-4
如果你正在处理URL,那么可以使用内置的URL类。
const url = new URL('https://foo.bar/');
console.log(url.toString()); // https://foo.bar

url.toString不会删除斜杠。 - Martin

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

2
subtring?除此之外,它还会删除第一个斜杠及其后面的所有内容。 - ThiefMaster
@ThiefMaster:真的吗?你不能看出我是指“substring”吗?同时,是的,我想删除第一个斜杠和它之后的所有内容,因为它符合所发布的问题和示例数据。 - josh.trow
他的评论说他想要移除末尾的斜杠。 - ThiefMaster
@ThiefMaster:根据他的示例,我的代码确实如此。 - josh.trow
1
只是一个提示,如果URL更改为“完全合格”的具有http://的URL,请勿在任何时候使用此功能,因为这将无法使用,并且具有中间斜杠/的任何链接都将无法使用(适用于谷歌搜索) - Barkermn01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接