How to Extract Numbers from a String in JavaScript
Extracting numeric values from a string is a common and essential task in data parsing. You might need to get a user ID from a log entry, a price from a product description, or a version number from a filename. The most powerful and flexible tool for all of these tasks is a regular expression.
This guide will teach you the modern, standard methods for using regular expressions to extract all numbers, the first number, or the last number from any string.
Goal 1: Extract All Numbers from a String
If you need to get every number present in a string, the String.prototype.match() method combined with a global regular expression is the perfect tool.
We use a regular expression to find all sequences of digits and then convert them to numbers.
match(/\d+/g): This finds all occurrences of one or more digits (\d+) in the string. Theg(global) flag is essential for finding all matches, not just the first.map(Number): Thematch()method returns an array of strings. We then usemap(Number)to convert each string in that array to anumber.
For example, we want to get all the numbers from a string, ignoring the text.
// Problem: How to get [123, 456] from this string?
const str = 'User ID: 123, Order ID: 456';
Recommended Solution:
function getAllNumbers(str) {
// Find all sequences of one or more digits
const matches = str.match(/\d+/g);
// If no matches are found, return an empty array
if (!matches) {
return [];
}
// Convert the array of string matches to an array of numbers
return matches.map(Number);
}
// Example Usage:
const str = 'User ID: 123, Order ID: 456';
const numbers = getAllNumbers(str);
console.log(numbers); // Output: [123, 456]
const noNumbersStr = 'hello world';
console.log(getAllNumbers(noNumbersStr)); // Output: []
Goal 2: Extract Only the First Number from a String
To get only the first number that appears in a string, we use a similar match() approach but without the global (g) flag.
The match() method, when used without the global flag, returns null if no match is found, or a "match object" (an array with extra properties) if a match is found. The first number will be at index 0 of this array.
We need to find only the first numeric value in a string.
// Problem: How to get just the number 100 from this string?
const str = 'Product: ABC, Price: 100, Stock: 50';
Recommended Solution:
function getFirstNumber(str) {
// The regex /\d+/ finds the first sequence of one or more digits.
const match = str.match(/\d+/);
// If a match is found, convert it to a number. Otherwise, return null.
return match ? Number(match[0]) : null;
}
// Example Usage:
const str = 'Product: ABC, Price: 100, Stock: 50';
const firstNumber = getFirstNumber(str);
console.log(firstNumber); // Output: 100
Goal 3: Extract Only the Last Number from a String
To get only the last number from a string, we can use a regular expression that matches all characters up to the final group of digits. This works by using a greedy pattern (.*) followed by a capturing group for digits (\d+).
The regex .*(\d+) finds the last number in a string.
-
.*: a Greedy match for any character (.), zero or more times (*). This will consume as much of the string as possible. -
(\d+): a capturing group that matches one or more digits. Because.*is greedy, this captures the last number in the string.
Recommended Solution:
function getLastNumber(str) {
// The regex captures the last number in the string
const match = str.match(/.*?(\d+)(?!.*\d)/);
// Return the captured number or null if not found
return match ? Number(match[1]) : null;
}
// Example Usage:
const str = 'Product: ABC, Price: 100, Stock: 50';
const lastNumber = getLastNumber(str);
console.log(lastNumber); // Output: 50
Conclusion
Regular expressions provide a powerful and flexible toolkit for extracting numbers from strings.
- To get all numbers, use
str.match(/\d+/g)and then convert the resulting array of strings to numbers. - To get the first number, use
str.match(/\d+/)and access the result at index0. - To get the last number, use the greedy
str.match(/.*(\d+)/)pattern and access the captured group at index1.
By choosing the right pattern, you can reliably parse any string to find the numeric data you need.