Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Capturing all digits in a string, and returning as a new string of digits

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?

like image 621
CodyBugstein Avatar asked Dec 03 '25 23:12

CodyBugstein


2 Answers

Just replace all the non-digits from the original string:

var s = "foo 123 bar 456";
var digits = s.replace(/\D+/g, "");
like image 71
Andrew Clark Avatar answered Dec 06 '25 14:12

Andrew Clark


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
like image 40
Mathletics Avatar answered Dec 06 '25 13:12

Mathletics



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!