JavaScript by Radu TM • June 21, 2022
function isValidNumber(str) {
// if the string is empty, it's not a valid number
if (str === "") {
return false;
}
// if the string contains anything other than digits, it's not a valid number
if (/\D/.test(str)) {
return false;
}
// if the string starts with 0 and is longer than 1 character, it's not a valid number
if (str.charAt(0) === "0" && str.length > 1) {
return false;
}
// if we get to this point, the string is a valid number
return true;
}
0
17.732
JavaScript by Radu TM • June 21, 2022
const isValidNumber = str => {
// check if string is empty
if (str === "") return false;
// convert string to number
const num = Number(str);
// check if string is a number
if (isNaN(num)) return false;
// check if number is finite
if (!isFinite(num)) return false;
// return true if string is a valid number
return true;
};
0
17.732