0

I am using window.location.href.indexOf to check if URL contains a string and works very well for something like this:

if (window.location.href.indexOf("franky") > -1) {
      alert("your url contains the name franky");

But it doesn't work to check if URL contains any number. The following always calls the alert, even if no number is in the 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"); }
  • try to use window.location.pathname – gaetanoM Feb 05 '21 at 15:08
  • use a regex: window.location.pathname.match(/\d/) != null --->contains a number – gaetanoM Feb 05 '21 at 15:10
  • What does the URL look like? Where is the number within it? Part of a route, or in a querystring value? – Rory McCrossan Feb 05 '21 at 15:13
  • Please add a [mcve] – Andreas Feb 05 '21 at 15:14
  • "The following always calls the alert, even if no number is in the URL." - That's because you are effectively testing against the existence of all numbers 0-9 in that example. That code translates to, "if the URL doesn't contain all numbers 0-9, then `alert("false")` – h0r53 Feb 05 '21 at 15:19
  • Little surprised no-one has mentioned this - change all your `||` to `&&` and you'll get what you want: https://jsfiddle.net/zkshm9dn/ or use your original condition: `> -1` with `||` – freedomn-m Feb 05 '21 at 16:02
  • You've changed the negativity of your test (from true to false) so you also need to swap the `||` to `&&`. If you kept it positive, then keep the `||`. You're saying *if it does not have 1 **or** it does not have 2* well it should be clear than if it's just "2" then it clearly doesn't have "1" so fails the first test. – freedomn-m Feb 05 '21 at 16:05

1 Answers1

5

As gaetanoM suggested, a regular expression would be the easiest way to do it.

if (window.location.href.match(/\d/)) {
  alert('contains a number');
} else {
  alert('does not contain a number');
}
PeteLe
  • 1,755
  • 10
  • 19