我有两个变量:

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

我怎么做呢?


当前回答

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

其他回答

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

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

试试这个:

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

function someFunction(site) {
  if (site.indexOf('/') > 0)
    return site.substring(0, site.indexOf('/'));
  return site;
}
function stripTrailingSlash(text) {
    return text
        .split('/')
        .filter(Boolean)
        .join('/');
}

另一个解决方案。