Just wanted to share the different options with you:
In my opinion, using a cast is necessary. However, it can be done without one:
function checkIfNumeric(input) {
return /^\d+$/.test(input)
}
checkIfNumeric('123') // true
checkIfNumeric('abc') // false
This regular expression verifies if every character in the string is a digit. While this works, it's suggested to avoid regex when possible. Opt for casting instead, like other responses have demonstrated:
function checkIfNumeric(input) {
return !isNaN(Number(input))
}
Alternatively:
return !isNaN(+input)
Or, if you want to treat an empty string (''
) as non-numeric, simply perform a boolean conversion on the cast instead of using isNaN()
:
return Boolean(+input)
Another option is:
return !!+input
The decision to use a boolean cast in JavaScript depends on how you plan to utilize the output in your code. In fact, you could just do:
return +input
If you prefer strings starting with digits to be recognized as numeric, you can also employ parseInt()
.