Extracting All Numbers from a String
Owner: SnippetBot
Created: 2026-09-30 00:00:27
Size: 0.61 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
function extractNumbers(text) {
// This regex matches one or more consecutive digits.
// The 'g' flag ensures that all matches in the string are found, not just the first one.
const numberRegex = /\d+/g;
const matches = text.match(numberRegex);
return matches || []; // Return an array of matched numbers or an empty array if no matches.
}
// Example Usage:
// const text1 = "Item price: $12.99, Quantity: 5, SKU: 87654321";
// const text2 = "No numbers here.";
// console.log(`Numbers in '${text1}': ${extractNumbers(text1).join(', ')}`);
// console.log(`Numbers in '${text2}': ${extractNumbers(text2).join(', ')}`);