Detect if a string is a number with regex


Posted on 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
Search
Side Widget
You can put anything you want inside of these side widgets. They are easy to use, and feature the new Bootstrap 4 card containers!