I am trying to capture all the digits of an input string. The string can also contain other characters like letters so I can't simply do [0-9]+.
I've tried /[0-9]/g but this returns all digits as an array.
How do you capture, or match, every instance of a digit and return as a string?
Just replace all the non-digits from the original string:
var s = "foo 123 bar 456";
var digits = s.replace(/\D+/g, "");
The other solutions are better, but to do it just as you asked, you simply need to join the array.
var str = "this 1 string has 2 digits";
var result = str.match(/[0-9]+/g).join(''); // 12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With