javascript - jquery href .indexOf,如何排除

标签 javascript jquery

假设我在 www.forum.com,除了主页之外,URL 总是包含各种附加文本,例如,www.forum.com/post1/oh-yeahwww.forum.com/post999/oh-baby 但我想创建一个 if 语句来排除除 www.forum.com 之外的所有内容,我该怎么做?

换句话说,如何做到这一点:

if ( href.indexOf('forum.com') === 'forum.com' ){
    console.log('href value is exactly forum.com, with no additional string');
} else {
    console.log('href url contains more than just forum.com');
}

谢谢。

最佳答案

当您调用href.indexOf('forum.com')时,结果是一个整数。如果您得到-1,那是因为它不存在。

The indexOf() method returns the position of the first occurrence of a specified value in a string. This method returns -1 if the value to search for never occurs. For more information

因此,您需要执行 (href.indexOf('/') = ,而不是 (href.indexOf('forum.com') === 'forum.com') = -1) 这意味着 www.forum.com

之后没有任何内容
if (href.indexOf('/') == -1) {
  console.log('href value is exactly forum.com, with no additional string');
} else {
  console.log('href url contains more than just forum.com');
}

此代码片段可能有帮助

href = "www.forum.com/test-1";

if (href.indexOf('/') == -1) {
  document.getElementById("test").innerHTML = "href value is exactly forum.com, with no additional string";
} else {  
  document.getElementById("test").innerHTML = "href url contains more than just forum.com";
}

href = "www.forum.com";

if (href.indexOf('/') == -1) {
  document.getElementById("test1").innerHTML = "href value is exactly forum.com, with no additional string";
} else {  
  document.getElementById("test1").innerHTML = "href url contains more than just forum.com";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="test">Test</p>

<p id="test1">Test</p>

关于javascript - jquery href .indexOf,如何排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552720/

相关文章:

javascript - 使用 mmenu 时无法添加页脚

javascript - 使用现有指令的 AngularJS DOM 操作

javascript - 如何在IE中设置HTML下拉列表的innerHTML

Javascript 导出类或对象

javascript - JavaScript 中的正则表达式匹配太多

JavaScript - 读取 XML 文档

javascript - 为什么在字符串化并解析回对象后缺少 getter/setter?

javascript - 如何在 jquery ui 中将图标放在 Accordion 中

javascript - 使用 jquery 选择选项在 IE 中不起作用?

javascript - Jquery 自动完成功能不适用于动态添加的行