Check if string contains only digits
Confirm whether a string is purely digits using the regex ^\d+$
with JavaScript's .test()
:
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 arace flag
.\d+
matches one or more digits (0-9), theracetrack
.$
represents the end of the string, ourfinish 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
:
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()
orparseFloat()
: 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:
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:
Was this article helpful?