这个话题在这里经常被讨论,但是我仍然找不到一个可行的解决方案。
我要检查URL:
If contains String=A, but not String=C redirect to ...
Else if contains String=B, but not String=C redirect to ...
Else if contains String=C redirect to ...
Else redirect to ...
我的代码是:
if (
window.location.href.indexOf('String=A') > -1 && !
window.location.href.indexOf('String=C') > -1 ) {
window.location.href = "/subpage/" + document.location.search + '?#onlya';
}
else if (
window.location.href.indexOf('String=B') > -1 && !
window.location.href.indexOf('String=C') > -1 ) {
window.location.href = "/subpage/" + document.location.search + '#onlyb';
}
else if (
window.location.href.indexOf('String=C') > -1 ) {
window.location.href = "/subpage/" + document.location.search + '#containsc';
}
else {
window.location.href = "/subpage/" + document.location.search + '#foundnothing';
}
我已经尝试过
window.location.href.indexOf('String=C') != -1
,依此类推。 实际发生了什么:
但是:
修改后的解决方案:
if (
window.location.href.indexOf('String=A') > -1 && !(window.location.href.indexOf('String=C') > -1 )
) {
window.location.href = "/subpage/" + document.location.search + '?#onlya';
}
else if (
window.location.href.indexOf('String=B') > -1 && !(window.location.href.indexOf('String=C') > -1 )
) {
window.location.href = "/subpage/" + document.location.search + '?#onlyb';
}
else if (
window.location.href.indexOf('String=C') > -1
) {
window.location.href = "/subpage/" + document.location.search + '?#containsc';
}
else {
window.location.href = "/subpage/" + document.location.search + '?#foundnothing';
}
答案 0 :(得分:1)
indexOf
返回找到的字符串的索引;如果找不到,则返回-1。
当您否定它时!除0以外的任何数字都将产生false
。
条件(给出字符串)!window.location.href.indexOf('String=C') > -1
等效于false > -1
的{{1}}
您可以通过将其包装为以下内容来获得预期的结果:
true
或通过使用波浪号双重否定
!(window.location.href.indexOf('String=C') > -1 )