1

I was trying to check a value that cames as a string is actually a string or a number and tried this:

let k = "a5b";
for(var i = 0; i < k.length; i++){
  var currentVal = k[i]
  if(typeof currentVal != " number"){
    console.log(currentVal + " is a letter")
  }
  else{
    console.log("its a number")
  }

}

But, it didn't work. I'm trying to implement this approach to check if a returned value in the form of a string is a number or a word. How could I make it detect wether there is actually a number inside or not?

Julio Rodriguez
  • 499
  • 6
  • 16

2 Answers2

2

I've fixed, check it..

let k = "a5b";
for(var i = 0; i < k.length; i++){
  var currentVal = k[i]
  if(isNaN(currentVal)){
    console.log(currentVal + " is a letter")
  }
  else{
    console.log("its a number")
  }
}
chandu komati
  • 795
  • 1
  • 5
  • 21
1

One option is to use the Number constructor and compare that to the value itself.

let k = "a5b";
for(var i = 0; i < k.length; i++){
  var currentVal = k[i]
  if(Number(currentVal) != currentVal){
    console.log(currentVal + " is a letter")
  }
  else{
    console.log("its a number")
  }

}
Nick
  • 16,066
  • 3
  • 16
  • 32