Detect if a string is a number with regex

River in the jungle
Reading Time: < 1 minutes

Regular expressions, commonly shortened to regex, are a powerful tool for working with text data in programming. One common task is determining whether a given string is a number. Fortunately, this is a task that can be accomplished with a relatively simple regex pattern.

To implement this regex pattern in code, simply use a regex matching function such as JavaScript’s `test()` method, which returns true or false depending on whether the pattern matches the input string. With this simple regex pattern, you can easily detect whether a given string is a number, making it a valuable addition to your programming toolkit.

/**
 * 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);
};

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

Examples

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

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

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: