简体   繁体   中英

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?

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

var s = "foo 123 bar 456";
var digits = s.replace(/\D+/g, "");

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM