【发布时间】:2021-02-05 15:06:38
【问题描述】:
我正在使用 window.location.href.indexOf 来检查 URL 是否包含字符串,并且非常适合这样的事情:
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
但它不能检查 URL 是否包含任何数字。 以下始终调用警报,即使 URL 中没有数字。
if (
window.location.href.indexOf("0") === -1 ||
window.location.href.indexOf("1") === -1 ||
window.location.href.indexOf("2") === -1 ||
window.location.href.indexOf("3") === -1 ||
window.location.href.indexOf("4") === -1 ||
window.location.href.indexOf("5") === -1 ||
window.location.href.indexOf("6") === -1 ||
window.location.href.indexOf("7") === -1 ||
window.location.href.indexOf("8") === -1 ||
window.location.href.indexOf("9") === -1
)
{ alert("false"); }
【问题讨论】:
-
尝试使用window.location.pathname
-
使用正则表达式:window.location.pathname.match(/\d/) != null --->包含一个数字
-
网址是什么样的?里面的数字在哪里?路线的一部分,还是在查询字符串值中?
-
"即使 URL 中没有数字,以下始终调用警报。" - 那是因为您正在有效地测试该示例中所有数字 0-9 的存在。该代码转换为“如果 URL 不包含所有数字 0-9,则
alert("false")
标签: javascript jquery url