How to check if a string in JavaScript contains only numbers

There is often the case that you want to check if a string in JavaScript contains only numbers or you might just want to extract the numbers from a string, but you want to do this extraction only when the string only contains numbers. The most common case for such check is when you want to read a value (returned as string from JavaScript) from an input field of a form and evaluate if this value is a number or not.

There is a solution for that and it is called cohersion. Even though there are no types in JavaScript, think cohersion as type casting from one type to another. In this case from string to number.

The first solution that someone might think of, is the parseInt(STRING) function which takes as parameter a string, extracts out and returns the numbers of this string. Consider the following example:

1
2
  var someString = "1234TestIt";
  var result = parseInt(someString); // result contains the value 1234

As we see the numbers are extracted from the string, however, this is not exactly what we wanted. We wanted this extraction to happen only when the string contained only numbers. JavaScript cohersion to the rescue:

1
2
3
4
5
  var someString = "1234TestIt";
  var result = +someString; // result is NaN
  
  var someOtherString = "1234";
  var result = +someOtherString; // result is 1234

By attaching a plus (+) at the beginning of the string we are converting the string into a positive number and since the string contains not only numbers but also characters the result is going to be NaN (not a number). In the second case we successfully extract the number out of the string.

If we want we can put the check into a function and use it as a guard check in if clauses:

1
2
3
4
5
6
7
8
9
  var someString = "1234TestIt";
  
  function checkIfStringIsANumber(string) {
    return !!+string;
  }
  
  if (checkIfStringIsANumber(someString)) {
    console.log("We found a number!");
  }

The !! coherses (explicit cohersion) the result into a boolean value and the function return true or false to an if clause.

comments powered by Disqus