How to extract numbers from a string
Short answer
match() with the g flag returns all matches. \d+ means one or more digits:
const text = 'Order 15 items for 230 dollars';
const numbers = text.match(/\d+/g).map(Number);
console.log(numbers);Output:
[
15,
230
]Decimal and negative numbers
Extend the pattern with an optional minus and an optional fractional part:
const text = 'Temperature fell from 2.5 to -3.75 degrees';
const numbers = text.match(/-?\d+(\.\d+)?/g).map(Number);
console.log(numbers.join(', '));Output:
2.5, -3.75Only digits
To get all digits as one string, for example from a phone number, remove everything else:
console.log('+1 (555) 123-45-67'.replace(/\D/g, ''));Output:
15551234567Common mistake
If there are no numbers, match() returns null, not an empty array. Add a fallback:
const numbers = 'no digits here'.match(/\d+/g) ?? [];
console.log(numbers.length);Output:
0Functions used in this recipe
- String.prototype.match — Finds matches of a regular expression.
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).
- Number() — Converts a value to a number.