假设我在 www.forum.com,除了主页之外,URL 总是包含各种附加文本,例如,www.forum.com/post1/oh-yeah 或 www.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/