Sometimes, we want to extract the number part of a string with JavaScript.
In this article, we’ll look at how to extract the number part of a string with JavaScript.
How to extract the number part of a string with JavaScript?
To extract numbers from a string with JavaScript, we can use the JavaScript string’s replace method.
For instance, we write:
const str = 'foo123bar456'
const number = str.replace(/D/g, '');
console.log(number)
to call str.replace with a regex that matches all non-digit characters and replace them with empty strings.
Therefore, number is '123456'.
Conclusion
To extract numbers from a string with JavaScript, we can use the JavaScript string’s replace method.
