我有两个变量:

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

我怎么做呢?


当前回答

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

单尾斜杠:

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

单个或连续的尾随斜杠:

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

单前导斜杠:

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

单线或连续的前导斜线:

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

单行斜杠和尾斜杠:

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

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

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

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

其他回答

试试这个:

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

我会使用正则表达式:

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

这里有一个小的url示例。

var currentUrl = location.href;

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

记录新的url

console.log(currentUrl);

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

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

以下片段更为准确:

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

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