Reputation: 23322
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?
Upvotes: 3
Views: 4508
Reputation: 213223
You can replace all the non-digits character rather than extracting the digits
:
var str = "some string 22 with digits 2131";
str = str.replace(new RegExp("\D","g"),"");
\D
is same as [^\d]
.
Upvotes: 1
Reputation: 208435
Just replace all the non-digits from the original string:
var s = "foo 123 bar 456";
var digits = s.replace(/\D+/g, "");
Upvotes: 3
Reputation: 36592
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
Upvotes: 1