【问题标题】:Javascript: find out if the URL is equal to a string, with or without trailing slashJavascript:判断 URL 是否等于字符串,带或不带斜杠
【发布时间】:2023-03-04 18:20:01
【问题描述】:

我在JS中有如下条件语句:

if(url === 'http://www.productionlocations.com/locations' || url === 'http://www.productionlocations.com/locations/')

我正在努力提高效率,所以我尝试了这个:

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

theurl = stripTrailingSlash(url);                   
if(theurl === 'http://www.productionlocations.com/locations')

但显然这只会使它变成更多代码:)

最有效的方法是什么?我之前尝试过使用 indexOf() ,但是没有用。感谢您的帮助!

【问题讨论】:

  • 条件语句不剥离任何东西。如果剥离不是必需的,请不要这样做!
  • 删除尾部斜线的更简单方法:str.replace(/\\$/, '')

标签: javascript string url


【解决方案1】:

你可以使用test方法:

if(/^http:\/\/www\.productionlocations\.com\/locations\/?$/.test(url)) {
    // code goes here
}

【讨论】:

  • 很难看到原始的测试 URL,如果 URL 发生变化,也很难维护。
  • 有超过 9000 种解决方案可供检查。我提供了我的;)
  • if(/\/locations\/?$/.test(url)) 是完全可行的。并实现相同的目标。
  • 是的,如果您不需要检查域。
猜你喜欢
  • 1970-01-01
  • 2011-10-04
  • 2016-08-24
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2014-09-16
  • 1970-01-01
  • 2017-07-04
相关资源
最近更新 更多