Check whether an input string contains a number in JavaScript
To swiftly verify if a string contains any numbers, use /\d/.test(input)
:
hasNumber
will be true
if InputHere
includes digits from 0-9, and false
otherwise.
Extended digit check scenarios
While searching for single digits is as unambiguous as it gets, scenarios when digits are embedded within more complex numbers (including negatives and floats) require a different approach.
Casting a wider detection net for numbers
Adding a sprinkle of regex magic, we can generate a pattern that is more inclusive:
Now -1
and 2.34
won't feel left out.
parseFloat() and parseInt() walkthrough
When using parseFloat()
and parseInt()
, keep in mind that they parse up to the first non-numeric character. parseFloat
gets along with floats, but parseInt
flat out stops at the decimal point. Here's what we mean:
Running numeric validation checks with isNaN
'isNaN' can come in handy when you want to ensure that a string represents a number and nothing more. In case you're dealing with an OCD scenario where everything needs to be spot on, this regex pattern might come in handy:
This check will only pass for numeric values, including positive or negative floats.
Number validation on-the-fly
When creating web apps, you might need to confirm that user input is numerical in real-time. JavaScript and libraries such as jQuery can help you keep an eye on those inputs:
Ensuring complete coverage through extensive tests
Throw in tests for a multitude of inputs, from the ordinary to the extraordinary:
- Single digits:
"7"
- Words with digits:
"abc123"
- Negative numbers:
"-42"
- Floating-point numbers:
"3.14159"
- Non-numeric strings:
"NaN"
or"infinity"
False positives: avoiding pitfalls and traps
Certain JavaScript functions can lead you astray by returning peculiar results. For instance, parseInt
will happily return a number from strings like "123abc"
. To avoid wrong turns and dead ends, make use of precise regex validation or smartly tie functions together.
Was this article helpful?