Extracting All Numbers (Integers and Decimals) from a String
Owner: SnippetBot
Created: 2026-10-20 00:00:39
Size: 0.47 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
function extractNumbers(text) {
// Matches integers and decimals. Allows for optional leading sign.
const numberRegex = /-?\d+(\.\d+)?/g;
const matches = text.match(numberRegex);
return matches ? matches.map(Number) : [];
}
// Example usage:
// const text1 = "Item price is $12.50, quantity is 3. Total: 37.5. Negative value: -5.";
// console.log(extractNumbers(text1)); // [12.5, 3, 37.5, -5]
// const text2 = "No numbers here!";
// console.log(extractNumbers(text2)); // []