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?
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
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]
.