Explain Codes LogoExplain Codes Logo

Check whether an input string contains a number in JavaScript

javascript
prompt-engineering
functions
regex
Anton ShumikhinbyAnton Shumikhin·Sep 17, 2024
TLDR

To swiftly verify if a string contains any numbers, use /\d/.test(input):

const hasNumber = /\d/.test('InputHere');

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:

const complexNumberPattern = /-?\d+(\.\d+)?/.test('InputHere');

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:

if (parseFloat('12.3abc') && isFinite('12.3abc')) { // 'parseFloat' is chill, it knows that 12.3 is a number. Cool story bro. } if (parseInt('123abc') && isFinite('123abc')) { // 'parseInt' does a 'mic drop' at the decimal point, thinking 123 is a number. }

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:

const strictlyNumeric = /^[+-]?\d+(\.\d+)?$/.test('Input');

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:

$('input').on('input', function() { const isValidNumber = /\d/.test($(this).val()); // Update the UI to reflect the validity });

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.