Check If a String Has Only Numbers in JavaScript

So you need to implement validation for your app’s frontend or backend. Here’s how to do it with RegEx.

Published Categorized as Coding, JavaScript

Suppose you want to check in JavaScript if a string contains only numbers.

What is the best way to do that?

With RegExp.test()

One of the best ways to check if a string contains only numbers in JavaScript is using the RegExp.test() method.

// Syntax for the RegExp method
RegExp.test(string);

The RegExp.test() method checks for a match between a regular expression (RegEx) and the specified string, and then returns the result as a Boolean value.

// Test if a string contains only 0 through 9
function checkForNums (input) {
  let result = /^\d+$/.test(input);
  console.log(result);
}

checkForNums('12345'); // Returns "true"

checkForNums('12c45'); // Returns "false"
checkForNums(''); // Returns "false"
checkForNums('-123'); // Returns "false"
checkForNums('1.2'); // Returns "false"

With the code above, we store a string in a variable named input and pass it onto the checkForNums function. Then, we test it for the digits 0-9 against a /^\d+$/ regular expression.

To break the RegEx down for you:

  • The first forward slash (/) is to open the RegEx and the last forward slash (/) is to close it.
  • The circumflex symbol (^) matches the beginning of the string to test and the dollar sign ($) matches its end.
  • \d stands for digit, all characters from 0 through 9. It is a shorter way to say [0-9], and the two can be used interchangeably.
  • The plus symbol (+) is a quantifier. It means that any of these digits must appear at least once in the string that’s being tested.

The test only needs to fail once for the function to do is job (test if a string has only numbers). If it fails once, we know that there’s a character other than 0-9 in the string, and so the string does not contain only numbers.

Edge Cases

Returns “False” on Empty String

If you pass an empty string onto the function above, it will return “false.”

This is because we’re using the plus symbol (+) as a quantifier in our regular expression, and the plus symbol demands that any digit from 0 through 9 must appear one or more times.

In case the test must return “true” for empty strings, you can refactor the RegEx to use the multiplication quantifier (*) instead, which stands for zero or more times:

// Test if a string has only numbers
function checkForNums (input) {
  let result = /^\d*$/.test(input);
  console.log(result);
}

checkForNums(''); // Returns "true"

Returns “False” on Negative Number

If you pass a negative number to the function above, it will return “false.”

This, obviously, is incorrect. But it helps to keep your RegEx nice and short if you’re absolutely sure your string can only contain positive numbers.

You can solve for this edge case by extending your regular expression to account for strings that contain digits and/or digits with a minus sign (-):

// Test if a string has only numbers
function checkForNums (input) {
  let result = /^\d*$|^-\d*$/.test(input);
  console.log(result);
}

checkForNums('123'); // Returns "true"
checkForNums('-123'); // Returns "true"

Returns “False” on Rational Numbers

If you pass a rational number to the function above, it will return false.

Once again, this is incorrect, but it helps to keep your test compact and performant if you can be sure that no real numbers will be passed on as a string to your function.

Now, if that isn’t the case, you can further augment your RegEx to account for positive numbers, negative numbers, and positive or negative rational numbers:

// Test if a string has only numbers
function checkForNums (input) {
  let result = /^-\d*$|^\d*$|^\d.*$|^-\d.*$/.test(input);
  console.log(result);
}

checkForNums('1.23'); // Returns "true"
checkForNums('-1.23'); // Returns "true"

With String.match()

Another way to test if a string has only numbers in JavaScript is to once again test the string against a regular expression, but this time using the String.match() method.

function checkForNums (input) {
  result = input.match(/^\d+$/) != null;
  console.log(result);
}

checkForNums('123'); // Returns "true"
checkForNums('1bc'); // Returns "false"
checkForNums(''); // Returns "false"

The RegEx in this function doesn’t account for negative or rational numbers. You can tweak the regular expression with the same tweaks we applied to that of the other function above.

In Conclusion

This is it! Whether you need to implement validation of a form on the frontend or backend business logic that prevents your application from breaking, I hope this tutorial helped you.

If you have any questions, came across other edge cases, or would like to share other solutions with the rest of this post’s readers, be sure to leave a reply below.

Image courtesy of iunewind /Depositphotos

Leave a comment

Your email address will not be published.