OneBite.Dev - Coding blog in a bite size

check if a string contains only numbers in Javascript

Code snippet on how to check if a string contains only numbers in Javascript

  const isStringNumber = (str) => {
    return /^\d+$/.test(str);
  }

This code uses a regular expression to check if a string contains only numbers. The function “isStringNumber” takes a single argument, ‘str’, which is the string to be tested. The regular expression ’/^\d+$/’ tests if the characters in the string are all numbers (from 0 to 9). If that expression returns true, the function “isStringNumber” will also return true, indicating the string passed to it consists only of numbers. If the regular expression returns false, the function will also return false.

javascript