How to detect if a string is a number with regex (with JavaScript example)

Backpacker hiking in nature
Reading Time: < 1 minutes

To detect if a string is a number with regex, you can use the following regular expression:

^-?\d+(\.\d+)?$

Explanation:

  • ^ matches the start of the string
  • -? matches an optional minus sign (-)
  • \d+ matches one or more digits
  • (\.\d+)? matches an optional decimal point followed by one or more digits
  • $ matches the end of the string

This regular expression will match any string that represents a number, including integers and decimal numbers, with or without a leading minus sign.


Here’s an example of how to use this regular expression to check if a string is a number in JavaScript:

function isNumber(str) {
  return /^-?\d+\.?\d*$/.test(str);
}

console.log(isNumber('42')); // true
console.log(isNumber('-3.14')); // true
console.log(isNumber('0')); // true
console.log(isNumber('4.2.1')); // false
console.log(isNumber('hello')); // false

The test method returns true if the regular expression matches the given string, and false otherwise.


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: