How to extract numbers from a string in JavaScript
Extracting numbers from strings is crucial for data parsing, form processing, text analysis, and implementing features like price extraction or numeric data validation in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented number extraction extensively in components like price calculators, data parsers, and validation systems where isolating numeric values from mixed text content is essential for processing.
From my extensive expertise, the most powerful and flexible solution is using the match()
method with regular expressions to identify and extract numeric patterns.
This approach handles various number formats and provides complete control over what constitutes a valid number in your context.
Use match()
with a regular expression to extract all numbers from a string.
const text = 'Price: $25.99 and quantity: 3 items'
const numbers = text.match(/\d+\.?\d*/g)
// Result: ['25.99', '3']
The match()
method with the regular expression /\d+\.?\d*/g
finds all numeric patterns in the string. The regex breaks down as: \d+
matches one or more digits, \.?
optionally matches a decimal point, \d*
matches zero or more digits after the decimal, and the g
flag finds all matches globally. In this example, it extracts both ‘25.99’ and ‘3’ from the mixed text. The result is an array of strings, which you can convert to numbers using map(Number)
if needed: numbers.map(Number)
would give you [25.99, 3]
.
Best Practice Note:
This is the same approach we use in CoreUI components for parsing form data, extracting prices from text, and processing numeric input across our component library.
For integers only, use /\d+/g
. For negative numbers, use /-?\d+\.?\d*/g
. To get actual numbers instead of strings, chain with map: text.match(/\d+\.?\d*/g)?.map(Number) || []
. The optional chaining ?.
handles cases where no numbers are found, preventing errors.