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"