Detect if a string is a number with regex


Aug 28, 2020
featured image

You can test this regex at https://regex101.com/

      

/**
 * It's not strictly the same than isNumber()
 *
 * @param text
 * @return true if the given text  is s number
 */
function isNumberText (text) {
    if (!text)  return false;
    // the value must be a number, including float and not empty.
    const reg = new RegExp('^-?\\d+\\.?\\d*$');
    return reg.test(text);
};
  

Examples

      
// it will return true on these cases
12
"12"
32.3
"43.4"

// false for these cases
"22a"
undefined
null
""
"1    2"
  

js regex util dev