There's no one built-in operation provided by default in JavaScript that matches a reasonable "is this string a number" definition (to my mind, anyway). You can get close with Number
, unary +
, or implicit conversion (just passing the string into isNaN
directly), with the caveat that they all do the same thing, which includes considering ""
to be 0
:
// Number
console.log(!isNaN(Number("10000"))); // true
console.log(!isNaN(Number("100T0"))); // false
console.log(!isNaN(Number(""))); // true (!)
// Same as implicit (here triggered with a unary +)
console.log(!isNaN(+"10000")); // true
console.log(!isNaN(+"100T0")); // false
console.log(!isNaN(+"")); // true (!)
// Same as implicit
console.log(!isNaN("10000")); // true
console.log(!isNaN("100T0")); // false
console.log(!isNaN("")); // true (!)
My answer to a related question goes into your options in detail.
Consequently, you can either do a regular expression (be sure to allow for scientific notation!) or a check for ""
up-front:
function toNumber(str) {
str = String(str).trim();
return !str ? NaN : Number(str);
}
console.log(!isNaN(toNumber("10000"))); // true
console.log(!isNaN(toNumber("100T0"))); // false
console.log(!isNaN(toNumber(""))); // false