我有两个变量:

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

我怎么做呢?


当前回答

以下片段更为准确:

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

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

其他回答

以下片段更为准确:

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

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

这里有一个小的url示例。

var currentUrl = location.href;

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

记录新的url

console.log(currentUrl);

试试这个:

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

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

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

我会使用正则表达式:

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是一个字符串。