Check if number with isNaN does not work

Asked

Viewed 80 times

0

I wonder if my URL has number (ID parameter).

get this:

rota = "/pessoa/editar/5";

after the substring

rota = "/pessoa/editar";
validarRota(rota)
{
  if(!isNaN(rota))
  {
    rota = rota.substring(0, rota.lastIndexOf("/"));
  }
}

But it doesn’t enter the if of isNaN.

What am I doing wrong?

Utilizo Angular 8.2

  • 1

    when using !isNaN you want to check if it is a number. To check when it is not a number, remove the !.

  • Man, Sam is right, you’re denying the return of function incorrectly.

  • 1

    The function isNaN does not serve to check if it has number. It serves to check whether or not it is a number.

  • then without the !, on other routes which have no number it is also entering if, for example pessoa/lista stays pessoa

  • 1

    Assuming that this 5 is a path parameter, it would not be better to use ActivatedRoute and check if the parameter is there (and if so, you see if only it is a number, without having to check the entire route)?

  • Testing isNaN('/pessoa/editar/5') and isNaN('/pessoa/editar'), both return true. That means the condition ! isNaN(rota) is false for these route values, then you will never enter the if. The function isNaN evaluates the whole string - just because it has a number on it, doesn’t mean that the whole string is also a number.

  • @hkotsubo, I’m not doing it directly where the route is... I do other things with the route in another Component and within this Component I need to do it up...

Show 2 more comments

1 answer

1


The way you are doing it won’t really work, in the comments other colleagues have already explained why, so I created the function below to try to help solve your problem.

function checkHasNumber(url) 
{
    var paths = url.split('/');
    var hasNumber = false;
    
    paths.forEach(function(value){
        if ("" != value && !isNaN(value)) {
            hasNumber = true;
        }	
    });
    
    return hasNumber;
}

var urlWithNumber = '/pessoa/editar/5';
var urlWithoutNumber = '/pessoa/editar/';


console.log(checkHasNumber(urlWithNumber));
console.log(checkHasNumber(urlWithoutNumber));

  • From your solution I managed to do what you need, thanks for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.