Explain Codes LogoExplain Codes Logo

Check if string contains only digits

javascript
regex
string-validation
functions
Anton ShumikhinbyAnton Shumikhin·Oct 2, 2024
TLDR

Confirm whether a string is purely digits using the regex ^\d+$ with JavaScript's .test():

const isDigitsOnly = /^\d+$/.test('12345'); // true...it's digit-tastic!

This regex asserts the string is non-empty and strictly numeric. Non-digit characters will return false, caught red-handed!

Breaking down the regex

The regular expression ^\d+$ is made up of:

  • ^ signifies start of the string, like a race flag.
  • \d+ matches one or more digits (0-9), the racetrack.
  • $ represents the end of the string, our finish line.

In combination, these elements ensure that every character within the string bounds is a digit.

Adapting the regex

While ^\d+$ is a one-size-fits-all solution, sometimes we need a custom fit:

  • Decimal numbers: ^\d+(\.\d+)?$ permits decimal points. Don't float away!
  • Numbers with commas : ^\d{1,3}(,\d{3})*$ accepts formats like "1,000" and "100". Cashier-approved!
  • Spaces: To handle leading or trailing spaces, use \s* as in ^\s*\d+\s*$.

Be sure to adjust your regex for specific use cases—think of it as your personal Swiss Army knife.

A reusable function

Increase your code reuse by extending String.prototype:

String.prototype.isDigitsOnly = function() { return /^\d+$/.test(this); // Like James Bond, it likes its digits shaken, not stirred! }; '12345'.isDigitsOnly(); // more truth than a lie detector! It's true. '12e45'.isDigitsOnly(); // false - it's sneaky, but we're sneakier!

Ensure to dodge naming conflicts when extending native prototypes. You don't want to step on any toes!

Beware of the disguised

Being ready for surprises is key. Here's a few places where patchy skies might lurk:

  • isNaN(): Unreliable as it stumbles upon strings like " " or "123e-1", returning false.
  • parseInt() or parseFloat(): These guys will convert as much of the string to a number as they can, perfect for a heist but not for validation.
  • + operator: Changing the type of a variable like a master of disguise can lead to false negatives.

Trust regex to stand guard, as it provides accurate matching and predictable results.

Regex – The knight in shining armor

Expand your use of regex to cover:

  • Credit card formats: ^(?:\d{4}-){3}\d{4}$ screens card numbers like "1234-5678-9012-3456".
  • ZIP code formats: ^\d{5}(-\d{4})?$ accepts 5-digit ZIP codes with 4-digit extension.

Regex, like a faithful knight, will always come to your rescue!

The no-regex path

If regex isn't your thing, get the job done using an array method:

const isDigitsOnly = (str) => str.split('').every(char => char >= '0' && char <= '9');

It’s a turtle race compared to regex, but for readability, some might say it's the hare's pal!

Testing your patterns

To vet your regex, utilize tools like regex101.com. Test against a variety of inputs to ensure precise results:

12345 ✔️ All-clear! Pure digits. 123.45 ❌ Fooled ya! Contains a hidden dot. 12e45 ❌ Almost had us! Notation isn't all digits.