gpt4 book ai didi

javascript - jquery href .indexOf,如何排除

转载 作者:行者123 更新时间:2023-11-28 18:50:31 24 4
gpt4 key购买 nike

假设我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com