Checking if a JavaScript string is a number is something that we have to do often.
In this article, we’ll look at how we can check if a JavaScript string is a valid number.
Write Our Own Function
We can write our own function to check if a string is a numeric string.
For instance, we can write:
const isNumeric = (str) => {
if (typeof str !== "string") return false
return !isNaN(str) &&
!isNaN(parseFloat(str))
}
console.log(isNumeric('123'))
console.log(isNumeric('abc'))
First, we check whether str
is a string or not with the typeof
operator.
This makes sure we’re checking a string instead of something else.
Then we call isNaN
to see if we can convert it to a number and then check if the converted value is a number.
If isNaN
returns false
, then we know there’s a good chance that it’s a number.
However, it can also just take the numeric part of a string and convert that to a number if the string starts with a number.
Therefore, we also need to call parseFloat
to parse the string into a number to make sure that the whole string is a number.
Then we can do the same check with isNaN
to make sure parseFloat
doesn’t return NaN
.
Therefore, the first console log should log true
.
And the 2nd console log should log false
.
Unary Plus Operator
We can also use the unary plus operator to convert a string into a number.
To do this, we write:
console.log(+'123')
console.log(+'123abc')
The first console log logs 123
And the 2nd console log logs NaN
.
The only catch is that an empty string converts to 0 with the unary plus operator.
parseInt
We can convert integer strings into an integer with parseInt
.
For instance, we can write:
console.log(parseInt('123'))
console.log(parseInt('123abc'))
They both log 123 since parseInt
will take the numeric part of the string if it starts with a number and convert that to a number.
But the string doesn’t start with a number, then it returns NaN
.
parseFloat
We can use the parseFloat
method to convert strings with decimal numbers to a number.
For instance, we can write:
console.log(parseFloat('123.45'))
console.log(parseFloat('123.45abc'))
They both log 123.45 since it also takes the numeric part of a string and tries to convert that to a number if the string starts with a number.
But the string doesn’t start with a number, then it also returns NaN
.
Regex Check
Since we’re working with strings, we can also use a regex to check whether the number is a numeric string.
For instance, we can write:
const isNumeric = (value) => {
return /^-?\d+$/.test(value);
}
console.log(isNumeric('123'))
console.log(isNumeric('123abc'))
The /^-?\d+$/
regex lets us check whether a string optionally starts with a negative sign with digits after it.
Therefore the first console log logs true
and the 2nd logs false
.
Conclusion
We can use regex or various built-in functions and operators to check whether a string is a number or not in JavaScript.