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

Dio*_*ion 3 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
Run Code Online (Sandbox Code Playgroud)

"/ names /"后面的数字的长度介于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))
Run Code Online (Sandbox Code Playgroud)

这很好用,但我有一种唠叨的怀疑,即创建"if"语句可能有更好/更清晰的方法.有没有办法可以压缩我当前的行,或者使用不同的代码以更简单的方式执行相同的操作,而不会使事情过于复杂?

ken*_*ytm 5

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

if (/names$/.test(document.URL))
Run Code Online (Sandbox Code Playgroud)

仅当"names"是URL的最后一部分时才会传递此条件,后面没有任何内容.的$匹配串的末尾的装置.