Explain Codes LogoExplain Codes Logo

Regex to check whether a string contains only numbers

javascript
regex-patterns
string-validation
regular-expressions
Anton ShumikhinbyAnton Shumikhin·Nov 1, 2024
TLDR

Check whether a string contains only digits using the regex pattern ^\d+$. This pattern is precise, quick, and matches strings that only contain digits.

// Trivia: Did you know "hello world" in binary is a string with only digits? const binaryHello = /^\d+$/.test('01101000011001010110110001101100011011110010000001110111011011110111001001101100'); // true const regularHello = /^\d+$/.test('Hello World!'); // false - Letters are rebellious; they don't conform to the binary world.

Empty strings can be marked as valid with ^\d*$.

Understanding regex components

Understanding the star * and plus + quantifiers

If the string can be empty, and you wish to match zero or more numerical characters, use ^\d*$. However, if you want to make sure a string has at least one numerical character and is not empty, switch to ^\d+$.

Handling the decimal drama and moody signs

To include optional signs and decimal points, the pattern /^-?\d*\.?\d*$/ steps in. Exclude empty strings before the decimal with the pattern /^-?\d+\.?\d*$/.

Handling various numerical formats

Whole lotta number or a fraction of it?

To validate both whole numbers and floating point numbers, ^\d+\.?\d*$ is the regex pattern to use. This covers a wider array of numeric inputs encountered in a dataset.

Beyond the standard: Currencies, percentages, and superstardom

As numeric representations grow complex (think currency or percentages), regex patterns too become detailed, matching the exact expected format effectively.

Practical applications and common scenarios

When you seek multi-digit supremacy

The original pattern ^[0-9]$ falls short when dealing with multi-digit strings like "123". Switch to ^[0-9]+$ or its shorthand ^\d+$ to validate numbers of different lengths.

The choice of optional decimals and signs.

Patterns like ^-?\d+\.?\d*$ become handy where decimals and signs are optional, covering common inputs in data fields.

Zero hero: Preventing leading zeros

To prevent strings with leading zeros, e.g., "007" (We ain't talking about James Bond here!), a pattern like ^[1-9]\d*$ ensures the string starts with a non-zero digit.

Proceed with caution: Pitfalls and complexities

The deceptive leading zeros

Watch out for leading zeros. The regex ^\d+$ does not discriminate against "007", might not fare well in certain contexts. Jump to a more specialized pattern in these cases.

Not all flags flap the same way

Using the .test() method with a regex featuring the global (g) flag can cause perplexity. Subsequent calls commence the search at the index of the last match.

The empty string enigma

Is an empty string ("") non-numerical? Such a decision might hold pivotal significance in certain scenarios.