Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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.75

Only 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:

15551234567

Common 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:

0

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.