jQuery如何判断当前页面的URL中是否包含指定的字符串?

8
4个回答

22

使用indexOf - 它将为所有以/about/开头的路径名返回true

if (document.location.pathname.indexOf("/about/") == 0) {
    //Code goes here
}

5
    if (document.location.pathname.indexOf("/about/") === 0) {
        //Code goes here
    }

这将检查确保pathname始终以该字符串开头。如果您想更具体地检查格式,则需要使用regex


0
有点挑剔,但为了以后的参考,更安全的做法是检查是否等于-1
  if (document.location.pathname.indexOf('/about') > -1) {
    // your Code
  }

0
我喜欢使用.includes方法。
if (document.location.pathname.includes('/about')) {
// your Code
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接