How to check if a string is a number
Short answer
Convert the string with Number() and check the result with Number.isFinite(). An empty string needs a separate check, because Number('') is 0:
const isNumeric = (value) => value.trim() !== '' && Number.isFinite(Number(value));
console.log(isNumeric('42'));
console.log(isNumeric('-3.5'));
console.log(isNumeric('12px'));
console.log(isNumeric(''));Output:
true
true
false
falseOnly digits
For a quantity, a PIN code or an id, check that the string consists of digits only:
const isDigits = (value) => /^\d+$/.test(value);
console.log(isDigits('0042'));
console.log(isDigits('4.2'));Output:
true
falseA range
After checking the format, check the limits:
const isValidAge = (value) => {
const age = Number(value);
return Number.isInteger(age) && age >= 0 && age <= 130;
};
console.log(isValidAge('35'), isValidAge('200'), isValidAge('3.5'));Output:
true false falseCommon mistake
parseFloat() reads the number from the beginning and ignores the rest, so it accepts strings that are not numbers:
console.log(parseFloat('12px'), Number('12px'));Output:
12 NaNFunctions used in this recipe
- Number() — Converts a value to a number.
- Number.isFinite — Checks that a value is a finite number (not NaN and not Infinity).
- parseFloat — Reads a floating-point number from the start of a string.