JAVASCRIPT
Extract All Numbers from a String
Learn to extract all sequences of digits from any string using a JavaScript regex, perfect for parsing IDs, numerical data, or cleaning user input.
function extractNumbers(inputString) {
const matches = inputString.match(/\d+/g);
return matches ? matches.map(Number) : [];
}
// Example usage:
const text = 'Order ID: 12345, Quantity: 7, Price: 99.99';
const numbers = extractNumbers(text);
console.log(numbers); // Output: [12345, 7, 99]
const noNumbers = 'No digits here';
console.log(extractNumbers(noNumbers)); // Output: []
How it works: The regex `/\d+/g` matches one or more digits (`\d+`). The `g` flag ensures that all occurrences are found, not just the first. The `match()` method returns an array of matched strings, which are then converted to numbers using `map(Number)`. If no numbers are found, the function gracefully returns an empty array.