How can I extract a number from a string in JavaScript?
To find digits in a string, apply match()
with the regex /\d+/
and convert the matches using parseInt()
:
Here, num
holds the first series of digits; result
returns the numeric conversion or null
if no digits are identified.
Come along on a regex journey
All roads leading to numbers
Want to trip across all numbers within a string? Here's how:
In this scenario, nums
becomes an array with your numeric loot, and map()
shifts it all into integers.
Keeping the band of numbers together
To retain sequential digits as a whole number:
After match()
scopes out the digits, join('')
lines them up into a digit conga line before parseInt()
conversion.
A good scrub for mixed content strings
For those messy strings, you need a cleanup:
The first replace()
says bye-bye to starting non-digits, while the next sweep expels any lingering alphanumerics, leaving "12345" primed for parseInt()
.
Handling a jungle of string formats
If your strings flaunt varied formats, construct your own path with a regex generator function:
Tips from the battlefront
Using parseInt
like a pro
Prevent surprise visits from unintended results by setting the radix in parseInt()
, especially if the string starts with "0":
Dancing with decimal points
For decimal numbers, use parseFloat()
and adjust your regex:
Tread lightly with non-matches
If digits are off for an outing, match()
returns null
. Mind your step:
This trap ensures result won't bite even if no digits are found.
Taming wild patterns
For complex extractions, tame your regex with named capture groups:
Named capture groups make your regex readable and your code cuddly.
Was this article helpful?