如何在单个“if”语句中压缩多个“indexOf”条件?

时间:2012-06-21 18:12:08

标签: javascript greasemonkey

我有一个函数,我想在访问特定的URL路径时运行,但是在该路径下面还有其他页面,我不希望脚本运行。例如:

website.com/names     **This is the only URL where the script should run**
website.com/names/24/places
website.com/names/648/groups
website.com/names/7340/questions

“/ names /”后面的数字的长度介于1和1之间。 n,但后三个示例是URL可能采用的唯一路径。我只希望脚本在用户位于“website.com/names”页面时运行,而不会出现“页面”之后的任何内容。截至目前,我将函数作为基于document.URL.indexOf的“if”语句,但感觉有点乱:

if(document.URL.indexOf("names") >= 0 && (document.URL.indexOf("places") == -1 && document.URL.indexOf("groups") == -1 && document.URL.indexOf("questions") == -1))

这很好用,但我有一种唠叨的怀疑,即创建“if”语句可能有更好/更清晰的方法。有没有办法压缩我当前的行,或者使用不同的代码以更简单的方式做同样的事情,而不会过度复杂化?

2 个答案:

答案 0 :(得分:5)

有些情况下应使用 正则表达式:)

if (/names$/.test(document.URL))

此条件仅在“names”是URL的最后一部分时才会通过,后面没有任何内容。 $表示匹配字符串的结尾。

答案 1 :(得分:1)

为什么不使用

检查 document.URL 末尾的名称
if (document.URL.indexOf("names") == len(document.URL)-5)

(除非len(document.URL)!= 4不能被假设......)。