0

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

1 回答 1

5

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

if (window.location.href.match(/\d/)) {
  alert('contains a number');
} else {
  alert('does not contain a number');
}
于 2021-02-05T15:15:18.210 回答