如何检查URL是否包含数字?

我正在使用 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"); }

回答

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

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


以上是如何检查URL是否包含数字?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>