JAVASCRIPT
Extract All Numbers (Integers & Decimals) from a String
Learn how to use regular expressions in JavaScript to efficiently extract all numeric values, including integers and floating-point numbers, from any given string for data processing.
function extractNumbers(text) {
const regex = /-?\d+(\.\d+)?/g;
const matches = text.match(regex);
return matches ? matches.map(Number) : [];
}
const text1 = "Order #123 for $45.99 was placed on 2023-10-27.";
const numbers1 = extractNumbers(text1); // [123, 45.99, 2023, 10, 27]
const text2 = "No numbers here!";
const numbers2 = extractNumbers(text2); // []
const text3 = "Temperatures: -5.2°C and 25°F.";
const numbers3 = extractNumbers(text3); // [-5.2, 25]
How it works: This snippet defines a function `extractNumbers` that uses a regular expression `/-?\d+(\.\d+)?/g` to find all integer and decimal numbers in a string. `-?` matches an optional minus sign. `\d+` matches one or more digits. `(\.\d+)?` optionally matches a decimal point followed by one or more digits. The `g` flag ensures all occurrences are found. The `match()` method returns an array of matched strings, which are then converted to actual numbers using `map(Number)`.