In this article, we will hand you the solutions on how to extract or get only numbers from a string in JavaScript with our easy-to-follow guide.
There a multiple ways to extract a numeric value from a string, to get the solutions keep on reading!
So, without further ado let’s get started to unlock the power of how to extract numbers from strings in JavaScript!
How to extract or get only numbers from a string in JavaScript?
To get a numeric value or to get only numbers from the string in JavaScript. Here are the following methods that provide different ways to extract numbers from a string in JavaScript.
Solution 1: Use the JavaScript match() method with regEx
The match() method in JavaScript can be used with a regular expression to find matches within a string.
let SampleString = "Itsourcecode0143456789";
let matches = SampleString .match(/(\d+)/); ✅
if (matches) {
console.log(matches[0]);
}
In our given example, we’re using the regular expression /(\d+)/ to match any sequence of digits (numbers) in the string.
This method returns an array containing all matches.
Output:
0143456789
Solution 2: Use the JavaScript replace() method with regEx
The replace() method in JavaScript is used to replace parts of a string with another string or a regular expression.
let SampleString= "Itsourcecode01434567890123";
let matches = SampleString.replace(/[^0-9]/g, ""); ✅
if (matches) {
console.log(matches);
}
In our given example, we’re using it with the regular expression /[^0-9]/g to replace all non-digit characters with nothing (effectively removing them), leaving only the numbers.
Output:
01434567890123
Solution 3: Use the JavaScript reduce() method with the spread operator
The reduce() method in JavaScript is used to reduce an array to a single value. It does this by executing a function for each value in the array from left to right. The return value of this function is stored in an accumulator.
let SampleString = "Itsourcecode01434567890";
let reference = "0123456789";
function check(x) {
return reference.includes(x) ? true : false;
}
let matches = [...SampleString ].reduce((x, y) => (check(y) ? x + y : x),""); ✅
if (matches) {
console.log(matches);
}
In this example, we’re checking if each character in the string is a number and if so, adding it to our final result.
Output:
01434567890
Conclusion
In conclusion, this article has provided you with various methods to extract or to get only numbers from a string in JavaScript.
We’ve shown you the usage of the match() method with regular expressions, the replace() method, and the reduce() method combined with the spread operator.
Each method has its own unique approach, but all are effective for this task.
We hope this article has provided you with enough information to understand the JavaScript get numbers from string.
If you want to explore more JavaScript topics, check out the following articles:
Thank you for reading Itsourcecoders 😊.