Checking Whether a Javascript String is a Number | Task

Ole Ersoy
Jun - 09  -  1 min

Scenario

We have a string "" and we want to check if it is a number.

Approach

Use this function:

function isNumeric(s) {
  if (typeof s != "string") return false
  // ... will return false for ""
  return !isNaN(s) && !isNaN(parseFloat(str)) 
}

The code !isNaN(s) will return true for "", so we also check whether we can parseFloat() it.

Demo