Javascript:判断 URL 是否等于一个字符串,有或没有尾部斜线

标签 javascript string url

我在 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(),但没有用。感谢您的帮助!

最佳答案

你可以使用test方法:

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

关于Javascript:判断 URL 是否等于一个字符串,有或没有尾部斜线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10553792/

相关文章:

python - 在导入的 .csv 中将字符串更改为 float

javascript - 在跨域中创建安全的 iframe

java - 从 url 字符串中检索一些文本并保存到一个单独的字符串

android - 从 URL 在 Android 的媒体播放器中播放视频

javascript - 如何为react-router Link的onClick函数执行设置超时?

javascript - 在 IE 中显示表格

java - Map.containsValue() 返回 false

Java 计算单词和字符

javascript - 为什么 2 == [2] 在 JavaScript 中?

javascript - 奇怪的 Nodejs 内存泄漏