JAVASCRIPT

Extracting All Numbers from a String

Learn to easily extract all numeric values, including integers and decimals, from any string using a concise JavaScript regex pattern.

function extractNumbers(text) {
  const numberRegex = /\b\d+(\.\d+)?\b/g; // Matches integers or decimals
  const matches = text.match(numberRegex);
  return matches ? matches.map(Number) : []; // Convert matched strings to numbers
}

// Examples:
const dataString = "The price is $123.45, with a discount of 10% on item ID 789.";
console.log(extractNumbers(dataString)); // [123.45, 10, 789]

const mixedString = "No numbers here, just text.";
console.log(extractNumbers(mixedString)); // []

const anotherString = "Value: 0.99 and 1000";
console.log(extractNumbers(anotherString)); // [0.99, 1000]
How it works: This `extractNumbers` function utilizes a regular expression `/\b\d+(\.\d+)?\b/g` to find and extract all integer and decimal numbers from a given string. `\d+` matches one or more digits. `(\.\d+)?` optionally matches a decimal point followed by one or more digits, making it suitable for both integers and decimals. The `\b` (word boundary) ensures that only whole numbers are matched, preventing partial number matches within words. 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)`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs