【问题标题】:How to check if the URL contains a number? [duplicate]如何检查 URL 是否包含数字? [复制]
【发布时间】: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


【解决方案1】:

正如 gaetanoM 所建议的,正则表达式是最简单的方法。

if (window.location.href.match(/\d/)) {
  alert('contains a number');
} else {
  alert('does not contain a number');
}

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2018-08-25
    • 2018-11-16
    相关资源
    最近更新 更多